Writing a secure copy designer with a smart pointer

I am trying to figure out whether it is possible to write a safe copy constructor using std::unique_ptrinside.
This is my code:

#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;
}

And the output for this code is:

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

So the question is, why is the destructor not called? I believe it std::unique_ptr<A> _awill go out of scope and the object must be destroyed.

+4
source share
1 answer

Stack deployment is only guaranteed if an exception is ever caught. If you add a try-catch block to yours main, you will see that the destructors got the correct name.

[Live example]

+9
source

All Articles