由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 容器中放置智能指针一问
相关主题
问个C++中重复删除指针的问题[C++] when destructors get called
弱问c++ iterator 和 pointer区别不如各位高手挑个专题讲讲C++11吧
容器里边放指针怎么办?Is it safe to use unique_ptr with STL container?
C++ pointer problem一个简单的小问题
shared_ptr处理stack上面的指针包含指针的类和vector的问题
今天给c++震惊了one more interview question
关于函数返回值的问题Interview question: is the following code OK?
c++ question菜鸟请教smart pointer
相关话题的讨论汇总
话题: ptr话题: unique话题: std话题: avec话题: 释放
进入Programming版参与讨论
1 (共1页)
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在程序运行期间一直不
: 销毁。
: 看来结论是,还是应该用智能指针。

1 (共1页)
进入Programming版参与讨论
相关主题
菜鸟请教smart pointershared_ptr处理stack上面的指针
一个Quant Developer的C++面试题今天给c++震惊了
请教智能指针shared_ptr implementation问题关于函数返回值的问题
Forward declaration with unique_ptrc++ question
问个C++中重复删除指针的问题[C++] when destructors get called
弱问c++ iterator 和 pointer区别不如各位高手挑个专题讲讲C++11吧
容器里边放指针怎么办?Is it safe to use unique_ptr with STL container?
C++ pointer problem一个简单的小问题
相关话题的讨论汇总
话题: ptr话题: unique话题: std话题: avec话题: 释放