大家好
我尝试使用字符串的初始化并获得了以下结果,我很想知道为什么会发生这种情况(结果在注释中)
#include <iostream>
using namespace std;
const string foo() {}
int main() {
const string a = foo();
string b = foo(); // Will make core dump
const string& c = foo(); // Will make core dump
string& d = foo(); // Compile error
const string& e = "HEY"; // Will make core dump
}
谢谢!
答案 0 :(得分:2)
const string a = foo();
string b = foo(); // Will make core dump
const string& c = foo(); // Will make core dump
string& d = foo(); // Compile error
所有这些都调用未定义的行为,因为声明foo()
返回const std::string
,但并非如此,程序的结果无关紧要。
答案 1 :(得分:1)
这应该有效:
#include <iostream>
using namespace std;
const string foo() {
return string();// TODO return sth useful
}
int main() {
const string a = foo();
string b = foo();
const string c = foo();
string d = foo();
const string d2 = "HEY";
}
让我们看看您做错了什么:
const string& c = foo();
您正在使用reference
初始化rvalue
,编译器将阻止这种情况,因为foo()
的结果是临时。
string& d = foo();
与上述相同的问题。 和
string& d = foo(); // Compile error
const string& d = "HEY"; // Will make core dump
您无法在同一范围内重新定义d
。
最重要的是,您的函数不会返回任何内容,这是未定义的行为:
const string foo() {}