拷贝构造与禁用-GCC 4.9编译通过

tech2026-09-29  0

拷贝构造在如下二种情况下被触发:

1. 对象需要通过另外一个对象进行初始化 2. 对象通过值传递方式进入函数 #include <stdio.h> class A { public: int* x; int y; A() = default; A (const A& a) { printf ("拷贝构造\n"); this->x = a.x; this->y = a.y; } A& operator= (const A& a) { printf ("赋值构造\n"); this->x = a.x; this->y = a.y; return *this; } A (int t) { x = new int (0); y = t; printf ("address: %x, point: %x, value: %d\n", this, x, y); } ~A() { printf ("delete %x\n", this); } }; A f () { A ret (3); printf ("stack address: %x, point: %x, value: %d\n", &ret, ret.x, ret.y); return ret; } void g (A ret) { printf ("stack address: %x, point: %x, value: %d\n", &ret, ret.x, ret.y); }

1.对象需要通过另外一个对象进行初始化

int main() { A a(1); A c = a; printf ("global address: %x, point: %x, value: %d\n", &c, c.x, c.y); return 0; } Output: address: 838e0840, point: 146dc20, value: 1 拷贝构造 global address: 838e0850, point: 146dc20, value: 1 delete 838e0850 delete 838e0840`

2.对象通过值传递方式进入函数

int main() { A a (1); g (a); return 0; } Output: address: aa99190, point: 10d5c20, value: 1 拷贝构造 stack address: aa991a0, point: 10d5c20, value: 1 delete aa991a0 delete aa99190

拷贝构造禁用 1.将拷贝构造函数声明为私有,并不予实现

class Uncopyable { private: Uncopyable(const Uncopyable &); // 阻止copying };

2.使用delete

class Uncopyable { Uncopyable(const Uncopyable &) =delete; // 阻止copying };
最新回复(0)