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

标签 c++ pointers operator-overloading actor rule-of-three

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

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

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

Program.exe has triggered a breakpoint

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

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

我不明白这是什么问题。

这是我的 Actor 类的样子:

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 释放,所以你正在做的是 未定义的行为.

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

关于c++ - 为什么删除 Actor 指针会导致 "Program.exe has triggered a breakpoint",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339275/

相关文章:

c++ - 使用 strchr 重载 >>

c++ - 为什么初始化列表只能用于声明?

c++ - std::array<T, 0> 的目的是什么?

将字符串从一个指针复制到另一个指针

c++ - 为结构定义 operator<

C++ Typedef 和运算符重载

c++ - 如何为 C 链接列表制作 C++ 包装器

c++ - 简单加密不起作用

pointers - 在 Fortran 中传递指针参数

c++ - 指针和新运算符