【发布时间】:2018-12-15 15:23:38
【问题描述】:
我对使用{} 初始化常量引用有点困惑。
所以这是我的代码:
#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 塔拉
编译器:
gcc 7.3.0
编译命令:
g++ -std=c++11 -O0 test.cpp -o test -Wall -pedantic
【问题讨论】:
标签: c++ reference curly-braces