为什么删除 Actor 指针会导致 "Program.exe has triggered a breakpoint"

Why does deletion of Actor pointer result in "Program.exe has triggered a breakpoint"

我正在尝试创建一个指向另一个 Actor 对象的 Actor 指针,如下所示:

Actor other = Actor();
Actor* ptr = &other;

然后,当我尝试 delete ptr 时,会导致运行时错误:

Program.exe has triggered a breakpoint

但是,当我创建一个新的 Actor 而不是将 ptr 分配给 other 的引用时,我可以安全地 delete 它而不会出现任何错误:

Actor* ptr = new Actor();
delete ptr;

我不明白是什么问题。

这是我的 Actor class 的样子:

Actor.h:

class Actor
{
  private:
    unsigned id;
    string name;
    vector< unique_ptr< Behaviour > > allBehaviours;
  public:
    Actor();
    virtual ~Actor();
    void Init(); // Go through all the behaviors and call their Inits and Ticks
    void Tick();
}

Actor.cpp:

#include "Planet.h"
#include "Behaviour.h"
#include "Actor.h"

Actor::Actor()
{
    win.GetCurrentPlanet()->AddActor(this);
    planet = win.GetCurrentPlanet();
}

Actor::~Actor()
{
    printf("Deleted Actor!");
    if (allBehaviours.size() > 0)
        allBehaviours.clear();
}

// Init and Tick and some getters, setters for name and id

我搜索了一下,发现了 The Rule of Three,但我不明白设置这样的指针时使用的是什么运算符:

Actor other = Actor();
Actor* ptr = &other;

我认为它是复制构造函数,但我的程序如何实现它?

And then when I try to delete ptr, it results in "Program.exe has triggered a breakpoint".

只有当指针指向的内存是通过调用 new 运算符在动态内存(即堆)中分配时,您才能对指针调用 delete

由于 other 是在自动内存(即堆栈)中分配的,它不能用 delete 释放,所以你正在做的是 未定义的行为.

当您的程序进入未定义行为领域时,任何事情都可能发生。理解程序的行为是徒劳的。