返回常量和核心转储的函数
function that return const and core dump
大家好
这是我的第一个问题,与大学课程有关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() {}
相关文章:
- 分段故障(堆芯转储)矢量
- Cppcheck生成xml转储文件
- 如何找出GDB的SIGTRAP核心转储的根本原因
- C++指针无法在函数外部传递值和分段错误(核心转储)错误
- 返回常量和核心转储的函数
- 从函数返回向量时C++中止(核心转储)
- 双向链表中的 AddToTail 函数会导致核心转储
- 在删除函数自由度的指针后,为什么我会得到核心转储
- 如何找到核心转储?将其缩小到构造函数和函数
- 分段核心转储C++,在构造函数中
- C++数据结构(标准库)转储(如 Python 打印函数)
- 具有复杂层次结构的decorator模式:导致核心转储的构造函数
- 运算符<<函数在转储成员函数方面的泛型实现
- 从函数返回时发生堆芯转储错误
- 分割错误(核心转储)在Ubuntu上使用c++上的矩阵函数
- 在 std::set<boost::uuids::uuid> 的析构函数中,我在 _int_free 中遇到了分段错误(核心转储)。为什么?
- 转储函数的内存
- 递归函数核心转储
- 数组列表和使用插入和检索函数的问题(段核心转储)
- 当main函数返回时转储核心