代码之家  ›  专栏  ›  技术社区  ›  Hello

为什么删除Actor指针会导致“Program.exe已触发断点”

  •  0
  • Hello  · 技术社区  · 7 年前

    我想创造一个 Actor 男演员

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

    然后,当我试图 delete ptr

    程序exe已触发断点

    但是,当我创建一个新的 而不是分配 ptr 参考 other ,我可以安全地 delete 它没有任何错误:

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

    我不明白问题出在哪里。

    这是我的 男演员 类看起来像:

    演员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 ,但我不明白在设置这样的指针时使用了什么运算符:

    1 回复  |  直到 7 年前
        1
  •  1
  •   Remy Lebeau    7 年前

    然后,当我试图删除ptr时,结果是“Program.exe触发了一个断点”。

    你可以打电话 delete new

    自从 other 而是在自动内存(即堆栈)中分配,不能用 删去 ,所以你要做的是

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