c++ - 为什么 Effective Modern C++ 的第 25 项中说 "no temporary std::string objects would arise"?

标签 c++ string c++11

Effective Modern C++ Item 25(170p~171p)中的代码如下:

class Widget {
public:
void setName(const std::string& newName) // set from
{ name = newName; } // const lvalue
void setName(std::string&& newName)     // set from
{ name = std::move(newName); }          // rvalue
…
};

w.setName("Adela Novak");

With the version of setName taking a universal reference, the string literal "Adela Novak" would be passed to setName, where it would be conveyed to the assignment operator for the std::string inside w. w’s name data member would thus be assigned directly from the string literal; no temporary std::string objects would arise.

我不明白如果调用采用通用引用的 setName 版本,为什么“不会出现临时 std::string 对象”。不应该将 newName 创建为临时 std::string 吗?

最佳答案

代码前面有

template<typename T>
void setName(T&& newName)             // newName is
{ name = std::forward<T>(newName); }  // universal reference

稍后出现您复制到问题中的代码。然后,在您引用的文字之前:

That would certainly work in this case, but there are drawbacks. [...] For example, consider this use of setName:

w.setName("Adela Novak");

紧接着:

With the overloaded versions of setName, however, [...]

文本是说除了您引用的代码之外,其他代码中不会出现临时字符串对象。您严重误读并因此错误引用了文本。

关于c++ - 为什么 Effective Modern C++ 的第 25 项中说 "no temporary std::string objects would arise"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368673/

相关文章:

c++ - 从模板类 Base<A> 派生类 A 以便 Base<A> 可以使用 A::B?

c++ - 编译时常量数组本身的编译时常量索引是编译时常量吗?

JAVA Unrecognized Character 第一行第一个字符

Python - 嵌套的 __repr__ 将换行符恢复为 "\\n"

string - 自动将 C 风格字符串解释为 std::string 到 Boost Property 树 .get 函数

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 放置复杂物体

ruby - 不知道为什么会发生这种情况

c++ - 哪些 C 结构出现在 std 命名空间中?

c++ - cpp迭代器继承