用智能指针编写安全的复制构造人

Writing safe copy-constructor with smart pointer

本文关键字:复制 安全 智能 指针      更新时间:2023-10-16

我试图弄清楚可以在内部std::unique_ptr的帮助下编写安全的复制构造函数。
这是我的代码:

#include <iostream>
#include <memory>
class A {
public:
  A():_a(10){
    std::cerr << "A() constructor" << std::endl;
  }
  A(const A& tmp){
    _a = tmp._a;
    std::cerr << "A() copy constructor" << std::endl;
  }
  ~A(){
    std::cerr << "~A()" << std::endl;
  }
  int _a;
};
class B {
public:
  B():_b(5){
    std::cerr << "B() constructor" << std::endl;
  }
  B(const B& tmp){
    std::cerr << "B() copy constructor" << std::endl;
    throw std::exception("exc");
  }
  ~B(){
    std::cerr << "~B()" << std::endl;
  }
  int _b;
};
class C {
public:
  C():a(nullptr),b(nullptr){
    std::cerr << "C() constructor" << std::endl;
  }
  C(const C& tmp){
    std::cerr << "C() copy constructor" << std::endl;
    std::unique_ptr<A> _a(new A(*tmp.a));
    std::unique_ptr<B> _b(new B(*tmp.b));
    a = _a.release();
    b = _b.release();
  }
  ~C(){
    std::cerr << "~B()" << std::endl;
  }
  A* a;
  B* b;
};
int main(int argc, char** argv){
  A a;
  B b;
  C c;
  c.a = &a;
  c.b = &b;
  C c2(c);
  return 0;
}

和此代码的输出:

A() constructor
B() constructor
C() constructor
C() copy constructor
A() copy constructor
B() copy constructor

那么,问题是为什么不调用灾难?
我想,std::unique_ptr<A> _a将脱离范围,并且应销毁对象。

仅在捕获异常时可以保证堆叠放松。如果您在main中添加了一个try-Catch块,则会看到驱动器被正确调用。

[LIVE示例]