C++:自动生成(默认)复制构造函数

标签 c++ operator-overloading copy-constructor

如果我声明一个类,(没有动态内存分配,没有指针):

class A{
  int a,b;
public:
  A();
  A(int,int);
  A& operator=(const A);
};

不声明拷贝构造函数安全吗?默认的复制构造函数是什么样子的?

A& A::operator=(const A other)
{
   a=other.a;
   b=other.b;
   return *this;
}

即使我没有声明复制构造函数,当我调用 operator=() 时也会调用默认复制构造函数


编辑:

默认的析构函数是:

A::~A(){}

所以这里不需要

最佳答案

规则是,如果您需要提供:

  • 复制构造函数或
  • 析构函数或
  • 复制赋值运算符

那么您可能需要提供全部三个。此规则称为 Rule of Three .


Is it safe not to declare a copy constructor?

这是安全的。

Do you have to for your example case?

不是真的。具体来说,三规则支配着这一点。查看链接的问题以获取更多详细信息。


How does the default copy constructor looks like?

我猜这是在问,默认复制构造函数是做什么的。
答案在:
C++03 标准 12.8 复制类对象:
第 8 段:

The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of copying is the same as the order of initialization of bases and members in a user-defined constructor (see 12.6.2). Each subobject is copied in the manner appropriate to its type:

— if the subobject is of class type, the copy constructor for the class is used;
— if the subobject is an array, each element is copied, in the manner appropriate to the element type;
— if the subobject is of scalar type, the built-in assignment operator is used.
Virtual base class subobjects shall be copied only once by the implicitly-defined copy constructor (see 12.6.2).


Even If I not declare a copy constructor, the default one will be called when I call operator=()

只有在需要创建类对象的拷贝时才会调用复制构造函数。这涉及在传递给函数或从函数返回时创建的对象的拷贝。
您的复制赋值运算符传递对象 A 按值,这种按值传递是通过复制构造函数传递对象的拷贝并因此调用复制构造函数来实现的。< br/> 为避免复制,您需要通过引用 传递:

A& A::operator=(const A& other)

好读:
What's the difference between passing by reference vs. passing by value?

关于C++:自动生成(默认)复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14754145/

相关文章:

c++ - 从构造函数传递给成员函数时,私有(private)成员变量为空

c++ - C/C++ : do built-in objects such as `int` `double` always stay in the exact place within memory in the duration of the program?

c++ - VC++ 中的光纤安全优化到底是什么?

c++ - 析构问题

C++:是否可以重载 |位于同一类中的两个不同枚举的运算符?

c++ - 如何重载运算符 <<

c++ - 如何复制或返回包含动态分配内存的对象?

c++ - 临时对象需要复制构造函数

c++ - 为嵌套类模板重载运算符<<

c++ - 在单链表C++中实现复制构造函数