为什么要调用复制构造函数?

时间:2020-04-26 17:01:47

标签: c++ copy-constructor

在下面的代码中,我创建了p1类的四个对象,分别为p2p3copyplayer,并打印了它们属性使用while循环,其代码和输出如下。但是我期望获得不同的输出,并且我不知道在前3种情况下我在哪里复制了对象。

#include <iostream>
using namespace std;
class player{
    public:
    int xp;
    string name;
    int health;

    player():player(0,0,"none") {} 
    player(int a):player(a,0,"none") {} 
    player (int a, int b, string c):name{c},xp{a},health{b} {}
    player (player &source)
    {
        name="copied player";
        xp=-1;
        health=-1;
    }
};
int main()
{
    player p1;
    player p2(2);
    player p3(2,5,"play3");
    player copy{p2};
    player arr[4]{p1,p2,p3,copy};
    int t=4;
    while(t--)
    {
        cout<<arr[3-t].name<<endl;
        cout<<arr[3-t].xp<<endl;
        cout<<arr[3-t].health<<endl;
    }
}

我得到以下输出:

copied player
-1
-1
copied player
-1
-1
copied player
-1
-1
copied player
-1
-1

但是,我期待的是:

none
0
0
none
2
0
play3
2
5
copied player
-1
-1

我不知道什么?

1 个答案:

答案 0 :(得分:3)

按照您的代码立场(以及注释中所指出的),在初始化arr[4]数组时,编译器会将 copy 初始化列表中的每个对象复制到目标-因此复制构造函数的调用四次。

避免这种情况的一种方法是在初始化列表中使用std::move(x),但是,您需要为player类提供一个move constructor(默认值就足够了) (根据您的情况)。

但是,请记住,从对象移开后,源对象不再必须与原来相同,并且使用它可能无效。移动后的唯一要求(尽管一个类可能会提供更多保证)是对象处于可以安全销毁的状态。 (感谢Jesper Juhl对本文的评论!)

此代码将产生您期望的输出:

#include <iostream>
#include <utility> // Defines std::move()
using std::string;
using std::cout; using std::endl;

class player {
public:
    int xp;
    string name;
    int health;

    player() :player(0, 0, "none") {}
    player(int a) :player(a, 0, "none") {}
    player(int a, int b, string c) :name{ c }, xp{ a }, health{ b } {}
    player(player& source) {
        name = "copied player";
        xp = -1;
        health = -1;
    }
    player(player&& p) = default; // Use the compiler-generated default move c'tor
};

int main()
{
    player p1;
    player p2(2);
    player p3(2, 5, "play3");
    player copy{ p2 };
//    player arr[4]{ p1,p2,p3,copy };
    player arr[4]{ std::move(p1), std::move(p2), std::move(p3), std::move(copy) };
    int t = 4;
    while (t--) {
        cout << arr[3 - t].name << endl;
        cout << arr[3 - t].xp << endl;
        cout << arr[3 - t].health << endl;
    }
    return 0;
}

注意:另请阅读:Why is "using namespace std;" considered bad practice?