C++ 复制构造函数和赋值运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5368258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:00:33  来源:igfitidea点击:

The copy constructor and assignment operator

c++constructoroperatorscopy-constructorassignment-operator

提问by Paul Manta

If I override operator=will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator=automatically 'inherit' the behavior from the copy constructor?

如果我重写operator=,复制构造函数会自动使用 new 运算符吗?同样,如果我定义了一个复制构造函数,是否会operator=自动“继承”复制构造函数的行为?

采纳答案by sgokhales

No, they are different operators.

不,他们是不同的运营商。

The copy constructor is for creating a new object. It copies a existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an old instance. It is not necessarily called when passing variables by value into functions or as return values out of functions.

复制构造函数用于创建一个新对象。它将现有对象复制到新构造的对象。复制构造函数用于从旧实例初始化新实例。当按值将变量传递给函数或作为函数的返回值时,不一定会调用它。

The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory.

赋值运算符是处理一个已经存在的对象。赋值运算符用于将现有实例更改为与右值具有相同的值,这意味着如果该实例具有内部动态内存,则必须销毁并重新初始化。

Useful link :

有用的链接:

回答by Erik

No. Unless you define a copy ctor, a default will be generated (if needed). Unless you define an operator=, a default will be generated (if needed). They do not use each other, and you can change them independently.

否。除非您定义复制构造函数,否则将生成默认值(如果需要)。除非您定义 operator=,否则将生成默认值(如果需要)。它们不相互使用,您可以单独更改它们。

回答by Alexandre C.

No. They are different objects.

不,它们是不同的对象。

If your concern is code duplication between copy constructor and assignment operator, consider the following idiom, named copy and swap:

如果您担心复制构造函数和赋值运算符之间的代码重复,请考虑以下习语,命名为copy 和 swap

struct MyClass
{
    MyClass(const MyClass&); // Implement copy logic here
    void swap(MyClass&) throw(); // Implement a lightweight swap here (eg. swap pointers)

    MyClass& operator=(MyClass x)
    {
        x.swap(*this);
        return *this;
    }
};

This way, the operator=will use the copy constructor to build a new object, which will get exchanged with *thisand released (with the old thisinside) at function exit.

这样,operator=将使用复制构造函数来构建一个新对象,该对象将在函数退出时*this与旧对象交换和释放(与旧的this内部)。

回答by Jonathan Wood

No, they are not the same operator.

不,他们不是同一个运营商。

回答by stijn

No.

不。

And definitely have a look at the rule of three(or rule of fivewhen taking rvalues into account)

并且一定要看看规则(或考虑右值时的五规则