使用智能指针编写安全的复制构造函数

tem*_*ema 4 c++ constructor smart-pointers c++11

我想弄清楚是否有可能在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;
}
Run Code Online (Sandbox Code Playgroud)

以及此代码的输出:

A() constructor
B() constructor
C() constructor
C() copy constructor
A() copy constructor
B() copy constructor
Run Code Online (Sandbox Code Playgroud)

所以,问题是为什么没有调用析构函数?
正如我想的那样,std::unique_ptr<A> _a将走出范围,对象应该被销毁.

Rei*_*ica 9

只有在捕获到异常时才能保证堆栈展开.如果向您添加try-catch块main,您将看到正确调用析构函数.

[实例]