使用此代码:
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移到那里的,但是我不确定这个答案也不是很确定。
在哪一行p被释放?
p
分配在哪一行?
您正在[[转让]]所有权q
,因此p
现在拥有资源。因此,一旦q
被破坏,即在函数f
的末尾,您的整数就会被破坏。[唯一指针本身在作用域的结尾处被破坏,即,p
在g()
返回时被销毁,而在q
返回时被销毁f()
。
#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;
}
程序输出为
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...