为什么这会在c++中导致段错误
Why does this cause a segfault in C++?
当我尝试将对象指针添加到std::列表指针时,我得到一个段错误。为什么?
object.h
#ifndef DELETEME_H
#define DELETEME_H
class Object
{
public:
Object(): yes(0) {};
int yes;
};
#endif
object.cpp
#include <list>
#include "deleteme.h"
int main()
{
std::list<Object*> *pList;
Object *pObject;
pObject = new Object();
pList->push_front(pObject);
}
pList
未初始化导致段故障
std::list<Object*> *pList; // You declared it but you have not said what
// value lives here.
所以当你尝试使用它时:
pList->push_front(pObject); // This is undefined behavior.
如果你把编译器的警告打开(up),编译器会警告你这是一个问题。你应该告诉编译器把所有的警告都当作错误来处理。
你是怎么解决的?
你应该创建一个列表。
std::list<Object*> *pList = new std::list<Object*>;
但是创建它作为一个指针是一个坏主意(不是一个非常坏的主意)。你刚刚打开了一个你不想处理的漏洞。你不应该(几乎不读(或者干脆不读))动态地创建内存。这会导致异常和泄漏等各种问题。在你理解所有权语义之前,坚持使用对象。
std::list<Object> pList;
pList.push_back(Object());
在注释中,您担心从函数返回它。
std::list<Object> getList()
{
std::list<Object> result;
result.push_back(Object());
result.push_back(Object());
return result;
}
int main()
{
// Technically this copies the list out of the function
// when the return is called (so your object and the list)
// must be copyable.
std::list<Object> data = getList();
// But in reality it will not be copied.
// Because the copiler will invoke NRVO and build it in place
// at the destination. If you put print statements in your objects
// constructor/destructor etc.. you can try and spot the copies.
// Turn on optimizations and any copies that did exist will be
// removed.
}
相关文章:
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 如何摆脱C ++中的分段错误错误?
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 如何解决分段错误错误C++
- 作为参数模板的模板类:MSVC 错误 - 错误 C2977:模板参数过多 (C++98)
- 安卓工作室 |CPP 文件错误错误: 位图库中对"AndroidBitmap_unlockPixels"的未定义引用
- 卷曲给出分段错误错误
- 无法访问 Arduino 结构字段。错误"退出状态 1。xxxx 不命名类型"
- 错误错误 C2872:"布尔值":kinect.h 的不明确符号
- C++打印模板容器错误(错误:"运算符<<"的不明确重载)理解?
- 结构的分割错误错误
- 为什么此代码返回分段错误错误?
- 错误错误:无法编译内置功能
- 分段错误错误C++
- C++ 1Z 错误:错误:演绎指南中声明中的显式限定
- 使用对数据类型的向量的哈希表中的分段错误错误
- 为什么此代码会导致分段错误错误
- JNA结构字段值错误
- C++段故障错误