问题描述
如果我让 unique_ptr
指向一个 STL 容器的实例会怎样?这段代码安全吗?
What if I make a unique_ptr
point to an instance of an STL container as follows? Is this code safe?
unique_ptr< vector<int> > p1( new vector<int> );
这不会导致 vector
的析构函数被调用两次,因为 vector
本身和 unique_ptr
都试图清理 vector
到目前为止获得的内存?这会导致未定义的行为吗?或者编译器是否知道 vector
已经释放了它的内存并且不会为了 unique_ptr
超出范围而再次调用析构函数?
Wouldn't this result in the destructor for the vector<int>
being called twice, since both the vector<int>
itself and the unique_ptr
both attempt to clean up the memory the vector<int>
had acquired so far? Could this result in undefined behavior? Or does the compiler somehow knows that that vector<int>
has released its memory and does not invoke the destructor again for the sake of the unique_ptr
going out of scope?
这只是为了理解,如果有人愚蠢到这样做,会不会很危险?
This is simply to understand that if someone was stupid enough to do this, could it be dangerous?
推荐答案
With unique_ptr<向量>p1( new vector );
unique_ptr
在 vector
上调用 delete
.vector
的析构函数将释放自己分配的内存.所以是安全的.
With unique_ptr< vector<int> > p1( new vector<int> );
the unique_ptr
with call delete
on the vector
.The destructor of vector
will then release its own allocated memory.So it is safe.
但是 vector
就足够了.我没有看到您想要 unique_ptr< 的情况.向量>
.
But vector<int>
is enough. I don't see a case where you'd want unique_ptr< vector<int> >
.
这篇关于指向 STL 容器的指针是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!