在延迟这个问题和调试几天后,我发现如果我的下面的代码在从 union (以及所有提到这个 vector 的代码)中删除 vector 之后运行,seg .故障消失。
#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();
}
For quick online IDE code test
这应该是另一个问题,但我认为它太简单了。 我以前听说过,如果在 union 中使用了一个非平凡的值,则应该注意是否切换了值,该怎么做,如果我不打算更改任何值,是否有必要在运行时?
编辑1
删除了 vector 和 std::function 的 union
编辑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; } }
和(感谢评论)像这样收集/替换并修复所有其他构造函数:
Task(std::string const &arg_0 = "", std::vector<Task*> *arg_1 = nullptr) { Name = arg_0; Subtasks = arg_1; }
经过一些讨论,问题的代码似乎存在设计缺陷:删除 vector 的内容是危险的,因为指针可能仍在被其他客户端使用,或者甚至可能没有分配,但是只引用局部变量。
为什么 Subtasks
首先是一个指针?为什么不删除呢?
关于c++ - 段。由指向结构指针的 vector 的指针引起的退出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39377977/