【问题标题】:Accessing pointees of a shared_ptr's in a deque owned by an object在对象拥有的双端队列中访问 shared_ptr 的指针
【发布时间】:2014-12-16 12:51:57
【问题描述】:

让一个对象 A 在 C++11 中拥有一个 shared_ptr 的双端队列。 要访问队列前面的指针属性和方法,我想获得对 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

但如果我使用对双端队列的中间引用,它会按预期工作

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

我觉得我真的错过了一些明显的东西......

【问题讨论】:

  • 只要您不与char*打交道,就不需要强制转换为uintptr_t
  • 您确定A::deque 是按引用返回而不是按值意外返回吗? ideone.com/gRw2bf 的行为符合预期。问题一定出在其他地方。
  • 这就是我发现的:A->deque() 作为成员双端队列的排序副本按值返回。编译器似乎对这个问题非常(太?)敏感,并且没有发出任何可能有帮助的警告。无论如何,谢谢。
  • 我将此作为答案发布,因此您可以接受。 (绿色标记)。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-05-21
    • 2019-11-11
    • 2016-09-25
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2020-11-19
    相关资源
    最近更新 更多