gpt4 book ai didi

c++11 - unique_ptr::operator= 在释放方面做了什么

转载 作者:行者123 更新时间:2023-12-03 08:07:23 24 4
gpt4 key购买 nike

我无法完全理解 unique_ptr 的赋值运算符。我知道我们只能移动它们,因为复制构造函数和赋值运算符被删除了,但是如果已经包含分配的 unique_ptr 被移动操作覆盖了吗?之前存储在智能指针中的内容是否被释放?

#include <iostream>
#include <memory>

class A{
public:
A() = default;
virtual void act() const {
std::cout << "act from A" << std::endl;
}
virtual ~A() {
std::cout << "destroyed A" << std::endl;
}
};
class B : public A {
public:
B() : A{} {}
void act() const override {
std::cout << "act from B" << std::endl;
}

~B() override {
std::cout << "destroyed from B " << std::endl;
}
};
int main() {
auto pP{std::make_unique<A>()};
pP->act();

==================== ! =======================
pP = std::make_unique<B>(); // || std::move(std::make_unique<B>())
==================== ! =======================

pP->act();
return 0;
}

当我做的时候

pP = std::make_unique<B>();

这是否意味着在第一行分配给 pP (new A()) 的内容会自动销毁?或者我应该选择:

pP.reset();
pP = std::make_unique<B>();

最佳答案

是的,请参阅 C++11 draft standard 的第 20.9.1 节第 4 段

Additionally, u can, upon request, transfer ownership to another unique pointer u2. Upon completion of such a transfer, the following postconditions hold:

  • u2.p is equal to the pre-transfer u.p,
  • u.p is equal to nullptr, and
  • if the pre-transfer u.d maintained state, such state has been transferred to u2.d.

As in the case of a reset, u2 must properly dispose of its pre-transfer owned object via the pre-transfer associated deleter before the ownership transfer is considered complete

换句话说,它会像您期望的那样在分配后自行清理。

关于c++11 - unique_ptr<T>::operator= 在释放方面做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com