簡體   English   中英

段 指向結構體指針向量的指針導致的退出錯誤

[英]Seg. Fault on exit caused by pointer to vector of pointers to struct

經過幾天的延遲和調試后,我發現,如果從聯合中刪除向量 (以及提及該向量的所有代碼)后,下面的代碼運行了。 故障消失。

#include <string>
#include <vector>
#include <functional>

struct Task
{
  std::string Name;

  std::vector<Task*> *Subtasks;
  std::function<void(std::string const &)> Job;

  Task() {}
  Task(std::string const &arg_0) { Name = arg_0; }
  Task(std::string const &arg_0, std::vector<Task*> *arg_1) { Name = arg_0; Subtasks = arg_1; }
  Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
  { Name = arg_0; Job = arg_1; }

  ~Task() { for (auto tItem : *Subtasks) { delete tItem; } }
};

class Console
{
private:
  std::vector<Task*> Routine;

public:
  ~Console() { for (auto tItem : Routine) { delete tItem; } } //I thought that this is not needed but Valgrind thinks otherwise, strangely the deconstructors of the Tasks are not called, I guess.

  void add(Task *arg_0) { Routine.push_back(arg_0); }

  void foo()
  {
    Task *tTask = new Task();
    //Task *tTask = new Task("Name");
    //Task *tTask = new Task("Name", [this](std::string const &arg_0){ ; });
   //Seg. fault still remains.
    add(tTask);
  }
};

int main()
{
    Console _Console;
    _Console.foo();
}

快速在線IDE代碼測試


這可能是另一個問題,但我認為這太簡單了。 之前我曾聽說過,如果在工會中使用了非平凡的事物,那么應該注意是否切換了值,如何進行切換以及如果我不打算進行任何值更改,則有必要這樣做在運行時?

編輯1

刪除了vector和std :: function的並集

編輯2

段。 錯誤很可能是由解構函數〜Task ()引起的

如果調用此構造函數:

Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
{ Name = arg_0; Job = arg_1; }

那么它崩潰肯定時,析構函數被調用,因為Subtasks未初始化。

~Task() { for (auto tItem : *Subtasks) { delete tItem; } }

固定:

Task(std::string const &arg_0, std::function<void(std::string const &)> arg_1)
{ Name = arg_0; Job = arg_1; Subtasks = nullptr;}

~Task() { if (Subtasks!=nullptr) for (auto tItem : *Subtasks) { delete tItem; } }

和(thx為注釋)收集/替換並修復所有其他構造函數,如下所示:

 Task(std::string const &arg_0 = "", std::vector<Task*> *arg_1 = nullptr) { Name = arg_0; Subtasks = arg_1; }

經過一番討論,似乎該問題的代碼中存在一個設計缺陷:刪除向量的內容很危險,因為指針可能仍被其他客戶端使用,甚至可能未被分配,而只是引用本地變量。 以及為什么Subtasks是指針? 為什么不刪除它?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM