将 boost::shared_ptr
声明到像 std::vector
或 std::list
这样的容器到底有什么意义?
这是一个使用 BOOST_AUTO
的例子。
void someFunction()
{
...
BOOST_AUTO(sharedPtrToContainer, boost::make_shared<std::vector<T>>());
...
}
如果只在本地需要容器,有什么意义吗?有什么好处?容器的 shared_ptr
有什么用?
最佳答案
What actually is the point of declaring a
boost::shared_ptr
to a container likestd::vector
orstd::list
?
与使用指向任何对象类型的共享指针完全相同;它允许您与其他范围共享对象的所有权。对象恰好是容器没有任何区别。
Is there any sense if you only need the container locally?
没有;如果你只在本地需要它,那么它应该是一个普通的自动对象。
What is the benefit? What would be the uses of a
shared_ptr
to a container?
如果你需要将它的生命周期延长到当前作用域之外,那么你需要动态创建和销毁它,然后它的生命周期应该由智能指针管理。
关于c++ - shared_ptr 对容器的意义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7065446/