简体   繁体   English

赋值运算符作为副本构造函数

[英]Assignment operator as copy constructor

Assignment operator can be used to copy the value of one object to another instead of using copy constructor,then why we required a copy constructor? 赋值运算符可用于将一个对象的值复制到另一个对象,而不是使用复制构造函数,那么为什么需要复制构造函数呢?

class example  
{
    int data;
public:
    example()
    {
    }

    example(int x)
    {
        data = x;
    }
};

int main()
{
    example a(50);
    example a(b);
    //same can be done with the assignment operator
    //b = a;
    return 0;
}

Because at the point of calling a copy constructor, the object being copied to doesn't yet exist. 因为在调用复制构造函数时,要复制到的对象尚不存在。

An assignment operator assigns the value of another object to one that does exist. 赋值运算符将另一个对象的值分配给一个确实存在的对象。

Devices such as member initialisation can be used with a copy constructor, but are not available on assignment. 诸如成员初始化之类的设备可以与副本构造函数一起使用,但是在分配时不可用。 Furthermore it's possible to create a const object using a copy constructor. 此外,可以使用复制构造const创建const对象。

Furthermore, the assignment operator typically returns a reference to self. 此外,赋值运算符通常返回对self的引用。

So a copy constructor and the assignment operator probably will leave the mutated object in an identical state, but it doesn't necessarily have to be the case. 因此,复制构造函数和赋值运算符可能会使变异对象保持相同的状态,但不一定必须如此。

As Bathsheba already said: A copy constructor creates a new object, an assignment operator assigns values to an already existing object. 正如Bathsheba所说:复制构造函数创建一个对象, 赋值运算符将值分配给一个已经存在的对象。 One needs to construct a new object, the other needs to handle whatever happens if you assign the values from one object to another. 如果您将值从一个对象分配给另一个,则一个需要构造一个新的对象,另一个需要处理发生的任何事情。 Take this example: 举个例子:

class Foo
{
  public:
    Foo(int x) { someValue = x; };
    int getValue() const { return someValue; };
  private:
    int someValue;
}

class Bar
{
  public:
    Bar(int y)
    {
        myFoo = new Foo(y);
        myValue = y + 1;
        myInitDone = true;
    };

    Bar(const Bar& other)
    {
        //myFoo was not yet initalized, so no need to clean it up
        myFoo = new Foo(other.myFoo->getValue()); 
        myValue = other.myValue;
        myInitDone = true;
    }

    Bar& operator=(const Bar& other)
    {
        delete myFoo; // If we don't clean up myFoo here we leak memory
        myFoo = new Foo(other.myFoo->getValue());
        myValue = other.myValue;
        // myInitDone is only set during construction due to [reason]
    }

  private:
    Foo* myFoo;
    int myValue;
    bool myInitDone;
}

The copy constructor needs to set myInitDone (which is only done during constuction because [insert reason here] ), while the assigment operator needs to clean up myFoo or it will leak memory. 复制构造函数需要设置myInitDone(仅在构造过程中完成,因为[在这里插入原因] ),而分配操作员需要清理myFoo否则它将泄漏内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM