y**b 发帖数: 10166 | |
h**l 发帖数: 168 | 2 better use emplace_back on new A(j) directly, then you don't need to create
a temporary unique_ptr variable.
the vector is a member variable of class B, it will not be destroyed until
its parent object is destroyed.
If it is not destroyed, the memory hold by those unique_ptrs will not be
released.
【在 y**b 的大作中提到】 : 请看伪码: : class A; : class B { : std::vector> aVec; : public: : do() { : for (int i = 0; i < 1000000; ++i) { : for (int j = 0; j < 1000; ++j) { : // method 1, rValue : // aVec.push_back()std::unique_ptr(new A(j));
|
y**b 发帖数: 10166 | 3 emplace_back确实很适合。
也就是说,容器不销毁,里面的unique_ptr也不会销毁并释放内存。
我的意思就是,仅就对于将指针放入容器的情况,将智能指针放入容器,
比起将内置指针放入容器,并没有什么好处啊,都得手动释放内存。
甚至是坏处,毕竟手动释放内置指针很容易,手动释放unique_ptr
还得先转换成内置指针后再手动delete。 |
y*****g 发帖数: 5 | |
y**b 发帖数: 10166 | 5 谢谢,很全面了。
发现make_unique是C++14才有的。 |
h**l 发帖数: 168 | 6 when the destructor of a container is called, the destructor of all its
elements will be called automatically. For smart pointer, its destructor
will release the resource it hold, for raw pointer, its destructor is a no-
op.
【在 y**b 的大作中提到】 : emplace_back确实很适合。 : 也就是说,容器不销毁,里面的unique_ptr也不会销毁并释放内存。 : 我的意思就是,仅就对于将指针放入容器的情况,将智能指针放入容器, : 比起将内置指针放入容器,并没有什么好处啊,都得手动释放内存。 : 甚至是坏处,毕竟手动释放内置指针很容易,手动释放unique_ptr : 还得先转换成内置指针后再手动delete。
|
y**b 发帖数: 10166 | 7 对,这是最大好处。只是我那个代码用不到这个好处,因为bObj在程序运行期间一直不
销毁。
看来结论是,还是应该用智能指针。 |
h**l 发帖数: 168 | 8 一方面是自动释放内存,另一方面是所有路径都自动释放 (return, exception, end
of scope)。 手动太麻烦。
不过性能会有问题,尤其是 shared_ptr
【在 y**b 的大作中提到】 : 对,这是最大好处。只是我那个代码用不到这个好处,因为bObj在程序运行期间一直不 : 销毁。 : 看来结论是,还是应该用智能指针。
|