c++ - 为什么要调用复制构造函数?
问题描述
在下面的代码中,我创建了 4 个名为p1
、p2
、p3
和copy
的对象,并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
我不知道什么?
解决方案
正如您的代码所代表的那样(并且正如注释中所指出的那样),当您初始化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;
}
注意:另请阅读:为什么是“使用命名空间标准;” 被认为是不好的做法?.
推荐阅读
- discord - 向角色中的每个用户写一封 DM
- google-app-engine - Google Cloud Scheduler 调用 API 的权限
- java - 如何发送带有模型的对象,包括其子对象
- python - 使用外部定义的函数/变量与内部方法/属性
- xml - SOAPUI:如何重用部分 XML
- c++ - 从 udp 接收帧对于人脸识别来说太慢了
- r - 如何在R中按组绘制二进制数据和颜色存在
- python - 如何在 python 中生成洛伦兹 2D 源
- reactjs - 具有依赖数组的 UseEffect 无限循环
- php - 避免在方法“up”中使用对类“\Illuminate\Support\Facades\Schema”的静态访问