如果两个构造之间存在差异

If there is a difference between two constructs

如果两个构造之间存在差异 我想知道

std::string name = std::string("Eugene");

std::string name = "Eugene";

C++11

首先让我们考虑一下语句:

std::string name = std::string("Eugene");

对于上面显示的语句,在 C++11 中有 2 种可能性。

  1. 类型std::string临时对象 是使用右侧的"Eugene" 创建的。然后,使用std::string的copy/move构造函数构造了名为name.
  2. 的对象
  3. 在 C++11 中,有 non-mandatory copy elision 这意味着允许实现省略右侧的临时变量。这意味着 而不是 在右侧创建一个临时对象,然后使用 copy/move 构造函数来构造 name,实现可以直接构造 name来自 "Eugene".

现在让我们考虑以下语句:

std::string name = "Eugene"; //this is initialization

在上面的语句中,一个名为 name 的对象是使用 字符串文字 和合适的 std::string 的构造函数构造的。

所以,在 C++11 中,你的问题的答案是两个语句之间存在差异 仅当 临时文件未被省略时。

C++17

在C++17中,有mandatory copy elison这意味着在这种情况下我们写:

std::string name = std::string("Eugene");

在上面的语句中,语言保证

No temporary on the right hand side is created. Instead, the object name is created directly using the string literal "Eugene" and a suitable std::string's constructor.

所以你的问题在 C++17 中的答案是两个语句之间没有区别