我在使用 {}
初始化常量引用时有些困惑。这是我的代码:
#include <iostream>
#include <initializer_list>
template <typename T>
class Test
{
public:
Test(std::initializer_list<T> l)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
Test(const Test<T>& copy)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
Test() = delete;
};
int main()
{
Test<int> t1 {100500};
//here temporary constructed with copy constructor
//ref1 bound to temporary
const auto& ref1 = {t1};
//no temporary, ref2 bound to t1
const Test<int>& ref2 = {t1};
//temporary constructed with copy constructor
//ref3 bound to temporary
const Test<int>& ref3 = {{t1}};
return 0;
}
我的困惑之源在于这3种初始化方式的不同行为。看起来它们执行不同的操作并遵循不同的规则。能否有人澄清每种情况下究竟发生了什么?
我的操作系统:
Linux Mint 19 Tara
编译器:
gcc 7.3.0
编译命令:
g++ -std=c++11 -O0 test.cpp -o test -Wall -pedantic