了解和使用副本分配构造函数

时间:2019-06-07 21:12:21

标签: c++ copy-assignment

我试图了解副本分配构造函数在c ++中的工作方式。我只使用过Java,所以我真的不在这里。我已阅读并看到返回参考是一种很好的做法,但是我不知道该怎么做。我写了这个小程序来测试这个概念:

main.cpp:

#include <iostream>
#include "test.h"

using namespace std;

int main() {
    Test t1,t2;
    t1.setAge(10);
    t1.setId('a');
    t2.setAge(20);
    t2.setId('b');

    cout << "T2 (before) : " << t2.getAge() << t2.getID() << "\n";

    t2 = t1; // calls assignment operator, same as t2.operator=(t1)

    cout << "T2 (assignment operator called) : " << t2.getAge() << t2.getID() << "\n";

    Test t3 = t1; // copy constr, same as Test t3(t1)

    cout << "T3 (copy constructor using T1) : " << t3.getAge() << t3.getID() << "\n";

    return 1;
}

test.h:

class Test {
    int age;
    char id;

    public:
        Test(){};
        Test(const Test& t); // copy
        Test& operator=(const Test& obj); // copy assign
        ~Test();
        void setAge(int a);
        void setId(char i);
        int getAge() const {return age;};
        char getID() const {return id;};
};

test.cpp:

#include "test.h"

void Test::setAge(int a) {
    age = a;
}

void Test::setId(char i) {
    id = i;
}

Test::Test(const Test& t) {
    age = t.getAge();
    id = t.getID();
}

Test& Test::operator=(const Test& t) {

}

Test::~Test() {};

我似乎不明白我应该在operator=()中放入什么。我见过有人返回*this,但从我读到的内容仅是对象本身的引用(在=的左侧),对吗?然后,我想到了返回const Test& t对象的副本,但是使用该构造函数没有意义吗?我返回什么,为什么?

3 个答案:

答案 0 :(得分:5)

  

我已阅读并看到返回引用是一种很好的做法,但我不知道该怎么做。

方法

添加

return *this;

作为函数的最后一行。

Test& Test::operator=(const Test& t) {
   ...
   return *this;
}

为什么

关于为什么您应该返回*this的问题,答案是它是惯用的。

对于基本类型,您可以使用以下内容:

int i;
i = 10;
i = someFunction();

您可以在链式操作中使用它们。

int j = i = someFunction();

您可以有条件地使用它们。

if ( (i = someFunction()) != 0 ) { /* Do something */ }

您可以在函数调用中使用它们。

foo((i = someFunction());

之所以起作用,是因为i = ...评估为对i的引用。即使对于用户定义的类型,也要保留这种语义是惯常的。您应该可以使用:

Test a;
Test b;

b = a = someFunctionThatReturnsTest();

if ( (a = omeFunctionThatReturnsTest()).getAge() > 20 ) { /* Do something */ }

但是然后

更重要的是,您应该避免为发布的类编写析构函数,副本构造函数和副本赋值运算符。编译器创建的实现对于Test就足够了。

答案 1 :(得分:2)

为了支持嵌套操作,需要返回对原始对象的引用。 考虑

a = b = c

答案 2 :(得分:2)

我们从赋值运算符返回一个引用,因此我们可以做一些很酷的技巧,例如@SomeWittyUsername shows

我们要返回引用的对象是被调用运算符的对象,即this。因此,就像您听到的一样,您将希望返回*this

因此您的赋值运算符可能看起来像:

Test& Test::operator=(const Test& t) {
    age = t.getAge();
    id = t.getID();
    return *this;
}

您可能会注意到,它看起来与复制构造函数极为相似。在更复杂的类中,赋值运算符将完成copy-constructor的所有工作,但此外,它还必须安全地删除该类已存储的所有值。

由于这是一个非常简单的类,因此我们不需要安全删除任何内容。我们可以重新分配两个成员。因此,这几乎与复制构造函数完全相同。

这意味着我们实际上可以简化您的构造函数,使其仅使用运算符!

Test::Test(const Test& t) {
    *this = t;
}

同样,虽然这适用于您的简单类,但在具有更复杂类的生产代码中,我们通常希望对构造函数使用初始化列表(有关更多信息,请阅读here

Test::Test(const Test& t) : age(t.getAge()), id(t.getId()) { }
相关问题