c++ - 删除类复制构造函数时无法使用等号表示法使用类构造函数
问题描述
在测试一些类时,我遇到了一个有趣的问题:当使用等号表示法 (=) 调用类构造函数时,如果删除了复制构造函数,则会遇到错误 error: copying variable of type 'Class' invokes deleted constructor。使用括号时,代码可以正常编译。
这里发生了什么?这可能是编译器错误吗?
考虑以下类:
class Test
{
public:
int Int;
public:
Test() = default;
Test(Test &) = delete;
Test(Test &&) = delete;
Test(int i)
{
Int = i;
}
};
构造函数调用如下:
Test t1(3); //No error
Test t2 = 3; //error: copying variable of type 'Class' invokes deleted constructor
只是为了检查我尝试添加一些检查并允许这些功能并编译代码。使用 MSVC以完全相同的方式编译的两个构造函数。
class Test
{
public:
int Int;
public:
Test()
{
Int = 0;
cout << "Constructor";
}
Test(Test &t)
{
Int = t.Int;
cout << "Copy Constructor";
}
Test(Test &&t)
{
Int = t.Int;
cout << "Move Constructor";
}
Test(int i)
{
Int = i;
cout << "Constructor from int";
}
};
Test t1(3); //Constructor from int
Test t2 = 3; //Constructor from int
这里到底发生了什么?
解决方案
推荐阅读
- flutter - 如何在 Flutter 中构建多个 UI 与一个项目略有不同的应用程序
- c++ - 返回类型为 ostream& 的函数的返回类型
- android - 列表视图未显示在 android 改造上,但编译器分配了 4MB 来编译 void android.widget.TextView。
- sinon - 使用参数验证对自身进行 Fake 的 CallOrder
- jquery - toggleClass 删除所有其他现有类
- excel - 基于值的重复行
- python - 如何将嵌套的 json 转换为数据框?
- vue.js - 我应该在 vue.js 中转储 data 属性中的所有变量吗
- python - 在字符串中查找单词
- android - 如何从视图模型中获取 val 中的编辑文本文本