Search code examples
c++pointersoperator-overloadingactorrule-of-three

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


I'm trying to create an Actor pointer that points to another Actor object, like so:

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

And then, when I try to delete ptr, it results in an runtime error:

Program.exe has triggered a breakpoint

But, when I create a new Actor instead of assigning ptr to the reference of other, I can safely delete it without any errors:

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

I don't understand what the problem is.

Here is what my Actor class looks like:

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

I've searched, and came upon The Rule of Three, but I don't understand what operator is used when setting a pointer like this:

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

I think it is the copy constructor, but how do I implement it for my program?


Solution

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

    You can call delete on a pointer only if the memory it is pointing at was allocated in dynamic memory (ie, the heap) by a call to the new operator.

    Since other is allocated in automatic memory (ie, the stack) instead, it cannot be freed with delete, so what you are doing is undefined behavior.

    When your program enters the realm of undefined behavior, anything can happen. It is futile to make sense of the behavior of the program.