c++ - 复制初始化:为什么即使关闭复制省略也不调用移动或复制构造函数?
问题描述
我的问题不同,因为我可能“知道”复制省略。我正在学习复制初始化。但是,下面的代码让我很困惑,因为我已经关闭了复制省略使用-fno-elide-contructors -O0
选项。
#include <iostream>
using namespace std;
class test{
public :
test(int a_, int b_) : a{a_}, b{b_} {}
test(const test& other)
{
cout << "copy constructor" << endl;
}
test& operator=(const test& other)
{
cout << "copy assignment" << endl;
return *this;
}
test(test&& other)
{
cout << "move constructor" << endl;
}
test& operator=(test&& other)
{
cout <<"move assignment" << endl;
return *this;
}
private :
int a;
int b;
};
test show_elide_constructors()
{
return test{1,2};
}
int main()
{
cout << "**show elide constructors**" <<endl;
show_elide_constructors();
cout << "**what is this?**" <<endl;
test instance = {1,2};//why neither move constructor nor copy constructor is not called?
cout << "**show move assignment**" <<endl;
instance = {3,4};
return 0;
}
我首先使用命令构建:
g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main
我得到的结果如下:
**show elide constructors**
move constructor
**what is this?**
**show move assignment**
move assignment
然后我用没有-fno-elide-constructor -O0
选项的命令进行构建,以证明g++
确实关闭了我之前构建中的优化。
那么,为什么test instance = {1,2}
不调用复制构造函数或移动构造函数呢?不是从隐式转换创建的临时对象吗?并且instance
应该由那个临时对象初始化?
解决方案
为什么
test instance = {1,2}
不调用复制构造函数或移动构造函数?
它不应该。test instance = {1,2}
是copy-list-initialization,作为效果,使用适当的构造函数(ie test::test(int, int)
)直接构造对象instance
。无需在此处构造临时并调用复制/移动构造函数。
推荐阅读
- algorithm - 了解这个地形相交算法
- reactjs - 使用 React-Router v6 进行身份验证后,如何将用户重定向回最初请求的页面?
- find - Git Bash在包含空格的文件夹和文件上递归查找exec
- android - 如何为线性recyclerView创建爆炸动画
- python - 使用 displacy 显示自定义实体
- python - requests.exceptions.HTTPError: 401 客户端错误 atlassian-python-api
- oracle - IO 错误:网络适配器无法在 MacOS Big Sur 上建立连接
- sql - Azure Synapse 按顺序处理 20k 条语句的最快方法
- java - 如何在 Java 中逐行处理对输出文件的输入?
- html - 如何在“step===2”中重用“step===1”模板