何时释放一个unique_ptr?

问题描述 投票:1回答:5

使用此代码:

void f(std::unique_ptr<int> q)
{
}

void g()
{
    std::unique_ptr<int> p{new int{42}};
    f(std::move(p));
}

在哪一行p被释放?我想在f函数的出口处说一下,因为它是使用std :: move移到那里的,但是我不确定这个答案也不是很确定。

c++ c++11 memory-management smart-pointers unique-ptr
5个回答
1
投票

在哪一行p被释放?


1
投票

p分配在哪一行?


0
投票

您正在[[转让]]所有权q,因此p现在拥有资源。因此,一旦q被破坏,即在函数f的末尾,您的整数就会被破坏。[唯一指针本身在作用域的结尾处被破坏,即,pg()返回时被销毁,而在q返回时被销毁f()


0
投票
为了清楚地更改您的代码段,请按照以下方式进行

#include <iostream> #include <memory> #include <utility> struct A { ~A() { std::cout << "~A()\n"; } }; void f(std::unique_ptr<A> q) { std::cout << "f() begins\n"; } void g() { std::cout << "g() begins\n"; std::unique_ptr<A> p{new A }; f( std::move( p ) ); std::cout << "p == nullptr is " << ( p == nullptr ) << '\n'; std::cout << "g() endss\n"; } int main() { std::cout << "Within main()\n"; g(); return 0; }

程序输出为

0
投票
p将在退出g函数时被销毁,就像其他具有局部作用域的变量一样。当时,它不再保存数据了。要理解,实际上您不需要单独的功能,只需考虑一下:

int* n = new int(42); { std::unique_ptr<int> p(n); // p how owns the value pointed to by n // for brevity, I'll say p owns n from now on, // although technically not correct... { // opening another scope! (corresponds to function call) std::unique_ptr<int> q; // another variable, nothing else is a // function parameter either... q = std::move(p); // this happens, too, when calling a function // at this point, the ownership is transferred to q // q now owns n, p is left with just nothing // (i. e. now holds a null-pointer) } // at this point, q is going out of scope; as it is the current // owner of n, it will delete it // q still is in scope, but it has transferred ownership, remember? } // at this point, q is destroyed; as it doesn't own anything at all any more // it dies without doing anything...

© www.soinside.com 2019 - 2024. All rights reserved.