std::string 如何管理这个技巧?
我刚刚写了一个函数:
void doSomeStuffWithTheString(const std::string& value) {
...
std::string v = value;
std::cout << value.c_str();
...
}
但是我用它来调用它
doSomeStuffWithTheString("foo");
并且它有效。所以我认为这个工作(一个 const char* 来初始化 std::string 的隐式实例)该值必须按值传递,但在这种情况下是按(const)引用传递的。
当引用为 const 时,是否有可能从 const char* 实例化隐式临时 std::string ?如果不是,那么这怎么可能行得通?
编辑
如果函数重载,
void doSomeStuffWithTheString(const char* value);
将选择编译器,会发生什么情况?
i just wrote a function:
void doSomeStuffWithTheString(const std::string& value) {
...
std::string v = value;
std::cout << value.c_str();
...
}
but then i call this with
doSomeStuffWithTheString("foo");
and it works. So i would have thought that this to work (a const char* to initialise a implicit instance of std::string) the value would have to be passed by value, but in this case is passed by (const) reference.
Is by any chance a implicit temporal std::string instantiated from const char* when the reference is const? if not, then how this possibly work?
EDIT
what happens if the function is overloaded with
void doSomeStuffWithTheString(const char* value);
which one will choose the compiler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
std::string
类型具有从const char*
的隐式转换(通过构造函数)。这就是允许字符串文字"foo"
转换为std::string
的原因。这会产生一个临时值。在 C++ 中,使用const &
作为临时值是合法的,因此这一切都结合在一起。可以使用您自己的 C++ 自定义类型来复制此技巧。
The
std::string
type has an implicit conversion (via constructor) fromconst char*
. This is what allows the string literal"foo"
to convert tostd::string
. This results in a temporary value. In C++ it's legal to have aconst &
to a temporary value and hence this all holds together.It's possible to replicate this trick using your own custom types in C++.
是的,临时
std::string
是根据字符串文字构造的。Yes, a temporary
std::string
is constructed from the string literal.确切地说,使用
std::string
默认构造函数Exactly, using
std::string
default constructor“该值必须按值传递,但在本例中是通过(常量)引用传递。”
有一个 C++ 功能,可以将临时值(在本例中为从
const char *
隐式转换的临时std::string
)传递给参数const 引用(在本例中为 const std::string &)类型。"the value would have to be passed by value, but in this case is passed by (const) reference."
There is a C++ feature where it is possible to pass a temporary value (in this case, a temporary
std::string
implicitly converted from theconst char *
) to an argument of const-reference (in this case,const std::string &
) type.