Re: prefix decrement on temporary object
On Jan 7, 8:26 am, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
Consider the code fragment:
vector<int> container;
container.insert(container.begin(), 10);
int& ref = *--container.end();
From this, it looks like we can apply prefix decrement operator to
container.end() - ie 'prefix --' can be applied to the iterator type
object which happens to be a temporary here.
In general can we apply prefix/postfix increment/decrement operator on
a temporary object of some class type ?
Kindly clarify.
Thanks
V.Subramanian
You can increment/decrement a temporary all you like, what is being
stored here is the resulting reference to an element. Some
implementations of std::vector use pointers as iterators, with
pointers - prefix decrement/increment may fail under certain
conditions (ie: passing the resulting temporary to a function). If
your vector implementation uses a iterator type instead of a pointer,
you'll be fine. Nonetheless, --container.end() is considered to be non-
portable.
Which then begs the question - why not use:
int& ref = container.back();
and since you appear to be pushing elements at front of vector, why
aren't you choosing a std::deque< int > instead?
#include <iostream>
#include <deque>
int main()
{
std::deque<int> container;
container.push_front(10);
container.push_front(9);
container.push_back(11);
int& ref = container.back();
std::cout << ref << std::endl;
}
Note: a deque does not store its elements in contiguous storage like
an array or vector. It has random iterators and op[] as well as at().