当我尝试编译以下函数时,我得到了错误.
string& foo(){
return "Hello World";
}
Error:
1 IntelliSense: a reference of type "std::string &" (not const-qualified) cannot be initialized with a value of type "const char [12]"
Run Code Online (Sandbox Code Playgroud)
Jam*_*nze 22
您的代码有两个问题.首先,"Hello World!"是一个
char const[13],而不是一个std::string.所以编译器必须(隐式)将其转换为std::string.转换的结果是临时的(在C++中是rvalue - 说),并且你不能用临时初始化对非const的引用.第二个是即使你可以(或者你声明函数返回对const的引用),你也会返回一个会立即超出范围(因而被破坏)的引用; 任何使用结果引用都将导致未定义的行为.
真正的问题是:为什么参考?除非你实际上指的是具有更长生命周期的对象中的某些东西,并且意图是客户端代码修改它(通常不是一个好主意,但是有一些值得注意的异常,比如operator[]向量),你应该按值返回.
小智 10
"Hello World"不是字符串,它是一个char数组.c ++编译器需要将其转换为字符串值,而不是字符串引用(因为它不是字符串),因此您的函数应如下所示:
string foo(){
return "Hello World";
}
Run Code Online (Sandbox Code Playgroud)
要扩展(根据OP的请求),编译器会执行以下操作:
string foo(){
char a[] = "Hello World";
string s( a );
return s;
}
Run Code Online (Sandbox Code Playgroud)
值s由std :: string复制构造函数复制出函数.