std :: string如何管理这个技巧?

lur*_*her 5 c++ pass-by-reference stdstring pass-by-const-reference

我刚写了一个函数:

void doSomeStuffWithTheString(const std::string& value) {
...
std::string v = value;
std::cout << value.c_str();
...
}
Run Code Online (Sandbox Code Playgroud)

但后来我称之为

doSomeStuffWithTheString("foo");
Run Code Online (Sandbox Code Playgroud)

它的工作原理.所以我认为这个工作(const char*初始化std :: string的隐式实例)该值必须通过值传递,但在这种情况下通过(const)引用传递.

当引用是const时,是否有任何机会从const char*实例化一个隐式的temporal std :: string?如果没有,那么这可能如何运作?

编辑

如果函数重载会发生什么

void doSomeStuffWithTheString(const char* value);
Run Code Online (Sandbox Code Playgroud)

哪一个会选择编译器?

Jar*_*Par 7

std::string类型具有隐式转换(通过构造函数)const char*.这是允许字符串文字"foo"转换为的内容std::string.这导致临时值.在C++中,拥有const &一个临时值是合法的,因此这一切都在一起.

可以使用您自己的C++自定义类型复制此技巧.

class Example {
public:
  Example(const char* pValue) {}
};

void Method(const Example& e) {
  ...
}

Method("foo");
Run Code Online (Sandbox Code Playgroud)