You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《Effective Modern C++》Item25中“无临时std::string对象”为何成立?

Why No Temporary std::string is Created with the Universal Reference setName

Let's start by clarifying what happens with the original two setName overloads you showed:

When you call w.setName("Adela Novak"), the string literal "Adela Novak" is a const char[]—not a std::string. Since neither of your original overloads accepts a const char[] directly, the compiler has to create a temporary std::string to convert the literal into a type that matches the const std::string& parameter. That's the temporary object you're expecting here.

Now, let's look at the universal reference version of setName, which would be written like this:

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

Here's the play-by-play of why no temporary is created:

  • Type deduction magic: The compiler deduces T to be exactly the type of the string literal: const char[11] (the 11 accounts for the 10 characters plus the null terminator). Thanks to C++'s reference collapsing rules, T&& ends up being an lvalue reference to that array (const char(&)[11]—string literals are lvalues, remember!).
  • Perfect forwarding preserves the type: std::forward<T>(newName) keeps the original array type intact. When we assign this to name (the std::string member), the array implicitly decays to a const char*.
  • Direct assignment via std::string's built-in overload: std::string has an assignment operator that takes a const char* directly: std::string& operator=(const char* s). This operator builds the string's content straight from the C-style literal—no need to create an intermediate temporary std::string first.

In short, the universal reference version doesn't force the literal to be converted to a std::string upfront. Instead, it lets the std::string's own assignment logic handle the literal directly, cutting out the temporary object entirely.

内容的提问来源于stack exchange,提问作者foo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:33:41