我有点困惑于C++11和C++17中构造函数的调用方式和原因。
#include <iostream>
using namespace std;
//---
template<typename T>
struct StructTest
{
public:
const T Var = -1;
//---
// constexpr StructTest() = delete; // 1
// constexpr StructTest() = default; // 2
// constexpr StructTest(const StructTest &Source) = delete; // 3
// constexpr StructTest(const StructTest &Source) = default; // 4
// constexpr StructTest(const StructTest &Source) {cout << "Copy" << endl;}; // 5
};
//---
StructTest<int> A{};
StructTest<int> A1{1};
StructTest<int> A2(A);
//---
int main(void)
{
return(0);
};
当我取消注释一些行时(使用clang编译器和c++17标准),我对发生的事情感到困惑:
- 1、编译成功。为
A
和A1
进行列表初始化,并为A2
使用默认复制构造函数。 - 2、编译成功。为
A
执行默认构造函数,为A1
进行列表初始化(?),并为A2
使用默认复制构造函数。 - 1 + 3或2 + 3、编译失败,因为
A2
的复制构造函数被删除了。 - 1 + 4、编译成功。为
A
执行默认构造函数,为A1
进行列表初始化(?),并为A2
使用默认复制构造函数。 - 2 + 4、编译成功。为
A
执行默认构造函数,为A1
进行列表初始化(?),并为A2
使用默认复制构造函数。 - 1 + 5、编译失败。提示
A
缺少(已删除)默认构造函数,并且没有匹配的构造函数可以用于A1
? - 2 + 5、编译失败。没有匹配的构造函数可以用于
A1
?
我认为我理解了大部分内容,但是我不明白为什么1 + 5和2 + 5编译失败。有人能解释一下编译器选择要使用的构造函数的逻辑以及为什么会编译失败吗?
如果我错误地认为在其他情况下被调用的构造函数,请指出实际被调用的构造函数以及原因。
StructTest<int> A{};
需要默认构造函数。 - user4581301