【发布时间】:2014-04-16 16:55:04
【问题描述】:
我有一个使用 boost::shared_ptr 的简单类结构。
它看起来像 -
点类:
boost::shared_ptr<PointPrism> getPrismFromDirection(const Point3& direction) const
{
return boost::shared_ptr<PointPrism>(new PointPrism(_position, direction));
}
boost::shared_ptr<PointPrism> getPrismFromAimingPoint(const Point3& aimingPoint)
{
boost::shared_ptr<PointPrism> prism = getPrismFromDirection((aimingPoint - _position).normalized());
prism->setAimingPoint(aimingPoint);
return prism;
}
主类:
main()
{
boost::shared_ptr<Point> p; //initialized somewhere in this code
boost::shared_ptr<PointPrism> prism = p->getPrismFromAimingPoint(aimingPoint);
//here it looks like the prism object is just fine
boost::this_thread::sleep(boost::posix_time::seconds(10));
//here both VS10 debugger and log prints show that values inside prism are corrupted
}
据我了解,这意味着代码中的某处 shared_ptr 引用计数被弄乱了,并且调用了析构函数,但我不知道在哪里。 有什么想法吗?
编辑 1:
当在 VS10 中按 Alt+Shift+F11 时在return prism; 行中断时(显示将要调用的所有函数),我同时看到了 boost::shared_ptr ctor 和 boost::shared_ptr dtor,其中(我认为)意味着我以错误的方式返回 shared_ptr 。有什么问题?
【问题讨论】:
-
您确定这些对象仅用于非拥有原始指针和从原始 shared_pointer 或彼此创建的共享/弱指针,而不是原始指针?
-
代码与描述的完全一样。此处未删除任何指针/引用。
-
如果您在
boost::this_thread::sleep调用之后添加另一个语句,您会看到这种行为吗? (例如:在main的最后一行添加int i = 0;,并在它处打断)。我猜这就是您记录值的方式,但我想我会仔细检查。 -
我在主函数中有一些其他调用,包括记录值。没有变化
-
调用 shared_ptr
的 dtor 和 ctor 并没有错。您正在退回它,它是复制构建并超出范围。这是正常行为。您应该将断点附加到 ~PointPrism() 并查看它何时被调用。如果它没有定义析构函数,则定义一个并执行。
标签: c++ boost shared-ptr