繁体   English   中英

const std :: unique_ptr管理的对象的生命周期

[英]lifetime of an object managed by const std::unique_ptr

我在std::unique_ptr参考中看到下面的注释:

只有非const unique_ptr才能将托管对象的所有权转移到另一个unique_ptr const std::unique_ptr管理的对象的生命周期仅限于创建指针的范围。

有没有人可以用一个例子来解释它? 我无法弄明白为什么。

你根本无法从const std::unique_ptr移动而且你不能使用其他修改成员函数 - swapreleasereset (这些在逻辑上是非const限定的,不能在const实例上调用)。

转移所有权意味着将旧所有者重置为非拥有状态,从而对其进行修改。


const std::unique_ptr将在其生命周期内(从初始化开始) 最多管理一个对象。
对于std::unique_ptr const& ,您将无法通过此引用(const正确性)从引用的(甚至非const) std::unique_ptr转移所有权。

resetreleaseswap和移动赋值函数是非const成员函数,因此不能与std::unique_ptr类的const实例一起使用。 因此, const std::unique_ptr无法被修改,并被强制拥有指针,直到它超出范围。

通常,您可以使用移动赋值或移动构造函数将托管对象的所有权转移到另一个unique_ptr ,例如:

std::unique_ptr<int> p(new int(1));
std::unique_ptr<int> q(std::move(p)); 
//now q owns the pointer, which is freed when q is destructed

但是如果pconst ,你就无法这样做,并且当p被破坏时,托管对象将被释放:

const std::unique_ptr<int> p(new int(1));
std::unique_ptr<int> q(std::move(p));  //compilation error

unique_ptr拥有它指向的内存。

void MyFunc()
{ 
    // Creates a unique pointer that points at a Foo object.
    std::unique_ptr<Foo> foo = std::make_unique<Foo>();

    // ... do some stuff, then return
}

在这个例子中,我们创建一个Foo对象并将其分配给unique_ptr 通常,当您创建堆上的内容时,必须在堆中使用new分配空间并构造它,并delete以破坏它并释放其空间。 这里,一旦你离开创建unique_ptr的范围(在这种情况下是函数的结尾), unique_ptr处理释放。

只有非const unique_ptr才能将托管对象的所有权转移到另一个unique_ptr。

这意味着您可以将指针的所有权转移到另一个unique_ptr ,但unique_ptr是它没有标记为const。 一次只能有一个unique_ptr拥有一个对象。

一种方法是这样的:

std::unique_ptr<Foo> foo1 = std::make_unique<Foo>();
std::unique_ptr<Foo> foo2 = std::move(foo1);

现在foo1的指针已移动到foo2 foo1不再管理那个内存, foo2就是。

const std :: unique_ptr管理的对象的生命周期仅限于创建指针的范围。

这意味着当您的unique_ptr离开作用域时,它会删除它指向的对象。 就好像你这样做了:

void MyFunc()
{ 
    Foo* foo = new Foo()

    // ... do some stuff, then return

    delete foo;
}

好处是,现在您不必手动调用delete,这很好,因为如果您忘记删除它,可能会发生内存泄漏。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM