gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:36:34 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com