在对象拥有的双端队列中访问shared_ptr的指针

时间:2014-10-21 10:18:46

标签: c++11 reference shared-ptr deque

让对象A在C ++ 11中拥有shared_ptr的deque。 要访问队列前面的指针属性和方法,我想获得对A-> deque()。front()的引用,但这似乎不像我期望的那样工作。

这是一个缩小问题范围的代码提取:只需显示使用shared_ptr get()方法获得的指针对象的地址,无论是使用副本还是引用。

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;

输出显示:

my_copy pointee: 7fa222c1be60
my_ref  pointee: 0           <---- Unexpected: should be the same as above

但如果我使用deque的中间引用,它会按预期工作

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;

输出显示:

my_copy pointee: 7fa222c1be60
my_ref  pointee: 7fa222c1be60

我的印象是我真的错过了一些明显的东西......

1 个答案:

答案 0 :(得分:0)

代码似乎是正确的,最可能的罪魁祸首是A::deque,它可能会按值返回。这会导致未定义的行为。该代码使用额外的引用,因为您将临时的生命周期延长到该引用的生命周期。