在大括号中返回构造函数参数?

Returning constructor arguments in braces?

我是 C++ 的新手,大括号初始化(或统一初始化)确实令人困惑。当函数 returns 大括号中的参数列表时究竟会发生什么?非常感谢您的澄清。

std::vector<double> foo()
{
  return {1, 2}; // is this the same as: std::vector<double>{1, 2} or std::vector<double>(1, 2)? or something else?
}

return {1, 2};,return 的值是 {1, 2}list-initialized,结果,returned std::vector<double> 包含 2 个元素值为 12.

return std::vector<double>{1, 2};, return 值为 copy-initialized from std::vector<double>{1, 2}, as the effect, the returned std::vector<double> contains 2 elements with value 1 and 2. In concept it'll construct a temporary std::vector<double> and the return value is copy-initialized from the temporary; because of mandatory copy elision (C++17 起) copy/move 操作被省略,效果与第一个完全相同案例.

return std::vector<double>(1, 2),return 值是从 std::vector<double>(1, 2) 复制初始化的,结果,returned std::vector<double> 包含 1 个具有值的元素2。强制复制省略在这种情况下也会生效。