首页 > 解决方案 > 为什么要调用复制构造函数?

问题描述

在下面的代码中,我创建了 4 个名为p1p2p3copy的对象,并player使用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

我不知道什么?

标签: c++copy-constructor

解决方案


正如您的代码所代表的那样(并且正如注释中所指出的那样),当您初始化arr[4]数组时,编译器会将初始化列表中的每个对象复制到目标 - 因此调用复制构造函数四次。

避免这种情况的一种方法是std::move(x)在初始化列表中使用,但要做到这一点,您需要为您的类提供一个移动构造函数player(在您的情况下,默认值就足够了)。

但是,请记住,在您从一个对象移动之后,源对象不再必须与原来相同,并且使用它可能无效。移动之后的唯一要求(尽管类可能会提供更多保证)是对象处于可以安全销毁的状态。(感谢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;
}

注意:另请阅读:为什么是“使用命名空间标准;” 被认为是不好的做法?.


推荐阅读