gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:32:05 25 4
gpt4 key购买 nike

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/

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