【问题标题】:Why does this cause a segfault in C++?为什么这会导致 C++ 中的段错误?
【发布时间】:2015-07-31 21:23:37
【问题描述】:

当我尝试将 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);
}

【问题讨论】:

  • 你还没有初始化pList。最好不要这样的指针。
  • 您声明了一个指向列表的指针,而不是初始化指针,也没有为指针分配任何指向的东西。
  • 停止所有指针。
  • 咳嗽..........你所展示的一切都不需要指针或new()
  • @deadpickle: (a) 你如何初始化一个指向anything的指针? (b) 不要。

标签: c++ segmentation-fault stdlist


【解决方案1】:

由于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());

在 cmets 中,您担心从函数中返回它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2017-08-18
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多