c++ - 移动构造函数需要但未使用,在数组初始化中使用已删除的复制构造函数的类元素
问题描述
我为冗长的标题道歉,但我无法简明扼要地表达这个问题。
我有一个带有delete
d 复制构造函数和复制赋值运算符的类。当我尝试使用类的实例初始化数组时,除非我提供移动构造函数,否则会出现编译器错误。但是,实际上并未调用提供的移动构造函数。
这是说明问题的MWE。
#include <cstdio>
#include <string>
class A
{
public:
explicit A(std::string s) : s_(s) { puts("constructor"); }
A() = delete;
~A() = default;
A(const A &other) = delete;
A &operator=(const A &other) = delete;
// A(A &&other) : s_(std::move(other.s_)) { puts("move constructor"); }
void print_s() { printf("%s\n", s_.c_str()); }
private:
std::string s_;
};
int main()
{
A arr[]{A{"some"}, A{"string"}};
for (auto &a : arr) {
a.print_s();
}
}
如图所示,将移动构造函数注释掉,我得到了错误:
> g++ file.cc -g -std=c++11 -o file && ./file
file.cc: In function ‘int main()’:
file.cc:22:32: error: use of deleted function ‘A::A(const A&)’
22 | A arr[]{A{"some"}, A{"string"}};
| ^
file.cc:10:2: note: declared here
10 | A(const A &other) = delete;
| ^
file.cc:22:32: error: use of deleted function ‘A::A(const A&)’
22 | A arr[]{A{"some"}, A{"string"}};
| ^
file.cc:10:2: note: declared here
10 | A(const A &other) = delete;
| ^
如果我取消注释移动构造函数,我会得到输出
constructor
constructor
some
string
因此,移动构造函数实际上并没有被调用。
为什么需要移动构造函数?我是否在某处犯了错误(例如,执行不善的移动构造函数)?
解决方案
和
A arr[]{A{"some"}, A{"string"}};
您正在创建两个临时A
对象,然后将它们复制/移动到数组中。现在,编译器可以优化此复制/移动,但该类仍然需要可复制/可移动才能发生。当您注释掉您的移动构造函数时,该类不再是可复制或可移动的,因此您会收到编译器错误。
应该注意的是,这在 C++17 中发生了变化,并保证了复制省略。对于无法复制或移动的类型,代码将在 C++17 及更高版本中编译。
如果你改变
explicit A(std::string s) : s_(s) { puts("constructor"); }
到
A(std::string s) : s_(s) { puts("constructor"); }
那么你的main
功能可能会变成
int main()
{
A arr[]{{"some"}, {"string"}};
for (auto &a : arr) {
a.print_s();
}
}
即使您无法复制或移动A
.
推荐阅读
- gulp - BrowserSync 将文件路径重定向到文件夹路径
- mysql - 从 WordPress 数据库中检索每个帖子的最新 10 张图像不起作用。可能的修复?
- react-native - 反应本机更改按钮颜色无法正常工作
- javascript - 如何使用 CodeceptJs 定位和输入 SimpleMde RichText 编辑器
- typescript - 断言对于 const 数组的每个值,一个对象都有一个键
- github - 如何在我的 github 托管网站上添加 google adsense?
- google-chrome - 从 HTTPS 页面访问 HTTP 图像源时来自 Chrome 87 的混合内容警告
- python - python asyncio aiohttp超时
- ethereum - solidity 将结构添加到数组并使用 web3 显示它没有按预期工作
- python - 实时更新烛台图表?