试图理解auto_ptr
Trying to understand auto_ptr
我试图了解auto_ptr类如何工作的某些细节。假设你有以下类(我在一个网站上找到了这个,该人解释了赋值运算符的细节)。
class TFoo : public TSuperFoo {
auto_ptr<TBar> fBar1;
auto_ptr<TBar> fBar2;
public:
TFoo& TFoo::operator=(const TFoo& that);
// various other method definitions go here...
}
现在是赋值运算符的实现。
TFoo& TFoo::operator=(const TFoo& that)
{
if (this != &that) {
auto_ptr<TBar> bar1 = new TBar(*that.fBar1);
auto_ptr<TBar> bar2 = new TBar(*that.fBar2);
fBar1 = bar1;
fBar2 = bar2;
}
return *this;
}
他接着说
在这里,如果第二个新操作失败,当我们退出函数时,第一个新的 TBar 将被 auto_ptr 的析构函数删除。但是,如果两个 new 都成功了,赋值将删除之前指向的对象 fBar1 和 fBar2,并且还将清零 bar1 和 bar2,以便在我们退出函数时它们的析构函数不会删除任何内容。
所以我的问题是为什么 bar1 和 bar2 会被归零?什么会触发它?你不必做这样的事情吗
fBar = bar1.release();
感谢您对此的任何帮助。
auto_ptr
的赋值运算符将对象的所有权转移给被分派者,从而有效地释放从中分配对象的auto_ptr
。因此,赋值运算符的语义相当违反直觉。这可能是auto_ptr
被弃用并应替换为unique_ptr
的主要原因。
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- CLANG 编译器 说:变量"PTR"可能未初始化
- 如何在自定义类中启用'auto loops'?
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 擦除许多矢量元素,同时使用'auto'
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 推理类型如何工作"auto"和按引用调用?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 'auto *x = new some_struct{};"是一个未初始化的变量?
- 为什么 std::gcd/lcm 返回 std::common_type_t<M, N> 而不是 auto?
- 将函数参数类型声明为 auto