为什么这会导致 C++ 中的段错误?
Why does this cause a segfault in C++?
当我尝试将对象指针添加到 std::list 指针时,出现段错误。为什么?
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.
如果您打开(向上)编译器警告,编译器会警告您这是一个问题。您真的应该告诉您的编译器将所有警告都视为错误。
你是怎么解决的
您应该创建一个列表。
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.
}
当我尝试将对象指针添加到 std::list 指针时,出现段错误。为什么?
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.
如果您打开(向上)编译器警告,编译器会警告您这是一个问题。您真的应该告诉您的编译器将所有警告都视为错误。
你是怎么解决的
您应该创建一个列表。
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.
}