Let an object A own a deque of shared_ptr's in C++11. To access the pointee properties and methods of the front of the queue, I would like to get a reference to A->deque().front(), but this does not seem to work as I would expect.
Here is a code extract to narrow the problem: just display the address of the pointee obtained with the shared_ptr get() method, either when using a copy or a reference.
auto const my_copy = A->deque().front();
cout<<"my_copy pointee: "<<hex<<reinterpret_cast<uintptr_t>(my_copy.get())<<endl;
auto const & my_ref = A->deque().front();
cout<<"my_ref pointee: "<<hex<<reinterpret_cast<uintptr_t>(my_ref .get())<<endl;
the output reads:
my_copy pointee: 7fa222c1be60
my_ref pointee: 0 <---- Unexpected: should be the same as above
But if I use an intermediate reference to the deque, it works as expected
auto const & my_deque = A->deque();
auto const my_copy = my_deque.front();
cout<<"my_copy pointee: "<<hex<<reinterpret_cast<uintptr_t>(my_copy.get())<<endl;
auto const & my_ref = my_deque.front();
cout<<"my_ref pointee: "<<hex<<reinterpret_cast<uintptr_t>(my_ref .get())<<endl;
the output reads:
my_copy pointee: 7fa222c1be60
my_ref pointee: 7fa222c1be60
I have the impression that I really missed something obvious...
The code seems correct and the most likely culprit is A::deque
which probably returns by value. This would cause undefined behavior. The code works with the extra reference since you are extending the lifetime of the temporary to the lifetime of that reference.