[英]Why does a const char* cast to std::string work?
This cast puzzles me: 这个演员让我困惑:
#include <string>
#include <iostream>
#include <memory>
using namespace std;
int main() {
string str1 = (string)"I cast this thing" + " -- then add this";
cout << str1 << endl;
}
Can someone explain why this c-style cast to string works (or is allowed)? 有人可以解释为什么这个c样式转换为字符串工作(或被允许)? I compared the generated optimized assembly with that from:
我将生成的优化程序集与以下内容进行了比较
string str1 = string("I construct this thing") + " -- then add this";
and they appear to be identical, so I feel like I'm forgetting some c++ semantics that actually allow this kind of cast/construction to be interchanged. 它们似乎是相同的,所以我觉得我忘记了一些c ++语义,它实际上允许这种类型的转换/构造互换。
std::string str2 = std::string("I construct this thing") + " -- then add this";
Yep, if you have a constructor that takes in a single argument like that it will be used to cast the argument type to the object type. 是的,如果你有一个构造函数接受一个像这样的参数,它将用于将参数类型转换为对象类型。 This is why we can pass
const char*
to functions taking strings. 这就是为什么我们可以将
const char*
传递给带字符串的函数。
A C-style cast will do a const cast and static cast or reinterpret cast whichever is possible. C风格的演员阵容将进行常规演员和静态演员或重新演绎演员。
A static cast will use a user-defined conversion if defined. 如果已定义,静态强制转换将使用用户定义的转换。
std::string
has a constructor string(const char *)
. std::string
有一个构造函数string(const char *)
。
The syntaxes std::string("something")
, static_cast<std::string>("something")
and (std::string)"something"
are equivalent. 语法
std::string("something")
, static_cast<std::string>("something")
和(std::string)"something"
是等价的。 They will all construct a temporary std::string
using the std::string::string(const char *)
constructor. 它们都将使用
std::string::string(const char *)
构造std::string::string(const char *)
构造一个临时的std::string
。 The only difference between the syntaxes would be when casting pointers. 语法之间的唯一区别是在转换指针时。
std::string
has a constructor in the form of std::string
有一个构造函数的形式
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
This acts as a conversion operator. 这充当转换运算符。 If you cast a string literal to a
std::string
it will call this constructor and create a temporary std::string
如果将字符串文字强制转换为
std::string
,它将调用此构造函数并创建临时的std::string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.