C++ 使用智能指针编写安全复制构造函数
我试图弄明白,在C++ 使用智能指针编写安全复制构造函数,c++,c++11,constructor,smart-pointers,C++,C++11,Constructor,Smart Pointers,我试图弄明白,在std::unique\u 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::unique\u 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;
}
所以,问题是为什么不调用析构函数?
我认为,
std::unique\u ptr\u a
将超出范围,应该销毁对象。只有在捕获异常时才能保证堆栈展开。如果将try-catch块添加到main
,您将看到析构函数被正确调用
如果您需要一个复制构造函数,
unique\u ptr
不是您选择的智能指针那么,问题是为什么不调用析构函数
因为您加入了B
的复制构造函数。@101010人们仍然希望引起这一问题的是\U a
的dtor被激发。请注意,前导下划线是保留的。尾随下划线很好,例如,a
而不是\u a
@JonHarper不,它们不是。前导下划线保留在全局范围内,或者后跟大写字母。但是名为\u a
的局部变量或成员变量是非常好的。
A() constructor
B() constructor
C() constructor
C() copy constructor
A() copy constructor
B() copy constructor