gpt4 book ai didi

c++ - 默认初始化与从默认构造值复制初始化

转载 作者:搜寻专家 更新时间:2023-10-31 00:28:39 26 4
gpt4 key购买 nike

thing 成为默认可构造和可移动构造的类型。考虑以下两个初始化:

thing t1;          // (1)
auto t2 = thing{}; // (2)
  • (1) 默认构造 t1

  • (2) 默认构造一个 thing 类型的临时对象,并将其移动到 t2 中。

(2)中的move在什么情况下会被省略?

在现代风格的 C++ 初始化中,类型通常根本不出现或出现在右侧。例如:

auto copy = vec;                              // Type doesn't appear

auto p_derived = std::make_unique<derived>(); // Type appears naturally on the right

// Putting the type on the right here makes it explicit that the upcast is intended
auto p_base = std::unique_ptr<base>{ std::make_unique<derived>() };

使用 (2) 将与这些样式一致,而使用 (1) 则不会。

此外,当使用 (1) 和长类型名时,变量名出现在最右边。使用(2)时,无论类型名多长,变量名都同样明显。

这是否意味着就一致性而言,(2) 优于 (1)?

最佳答案

哪个更好,见仁见智。我不会权衡,这不是 SO 的目的。

每个支持 C++11 的现代编译器都会省略该移动,除非您传递明确的编译器标志以永不省略任何内容。

在 C++17 中没有省略的 Action ; thing{} 是纯右值,纯右值不是 C++17 中的对象,而是创建对象的指令(可能实例化匿名临时对象,但在本例中不是)。

auto x = prvalue ; 语句导致使用 prvalue 指令构造 x

关于c++ - 默认初始化与从默认构造值复制初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44357272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com