用智能指针编写安全的复制构造人
Writing safe copy-constructor with smart pointer
我试图弄清楚可以在内部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示例]
相关文章:
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 将对象的字节复制到数组并再次复制回来是否安全
- 适用于大型数组的无复制线程安全环形缓冲区
- std::shared_ptr::unique(),复制和线程安全
- 将类复制到未初始化的内存中是否安全?
- 各种 OpenCL 样板类型是否可以安全复制
- 标准::atomic_应该如何...<std::shared_ptr>用于线程安全类的复制和移动操作?
- std::shared_ptr 复制构造函数线程安全
- 用智能指针编写安全的复制构造人
- 安全复制对象的替代方案
- 类层次结构可以安全且琐碎地复制吗?
- boost中的线程安全可复制循环缓冲区
- 'const'双重复制+比较安全吗?
- 以理智、安全和高效的方式复制文件
- 复制/修改STL容器的副本是线程安全的
- 是c++中线程安全的默认复制构造函数
- 安全的字符串复制超过DLL边界
- 是复制线程安全的
- 如何在c++中使用std::list迭代器存储在std vector中,创建复制安全容器
- 当复制一些大于dst的内容时,memcpy()是否安全