当我尝试将一个Object指针添加到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);
}
答案 0 :(得分:2)
它会导致段错误,因为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.
}