返回常量和核心转储的函数

function that return const and core dump

本文关键字:函数 转储 核心 常量 返回      更新时间:2023-10-16

大家好

这是我的第一个问题,与大学课程有关C++

我尝试使用字符串的初始化并得到以下结果,我很想知道为什么会发生这种情况(结果在评论中(

#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
}

谢谢!注意:它不是有效的代码

用作大学的练习

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但事实并非如此,程序的结果无关紧要。

这应该有效:

#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();

您正在使用rvalue初始化reference,编译器将阻止这种情况,因为foo()的结果是暂时的。

string& d = foo();

与上述相同的问题。和

string& d = foo(); // Compile error
const string& d = "HEY"; // Will make core dump

您不可能在同一范围内重新定义d

最重要的是,你的函数不返回任何内容,这是未定义的行为:

const string foo() {}