0

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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Drin
  • 3
  • 3
  • 1
    `other` located in stack, and memory must not be deleted. default `delete` implementation try free memory from heap. and heap manager triggered breakpoint when you try free invalid pointer. – RbMm Jul 27 '17 at 00:08
  • Regarding the Rule of Three, `Actor other = Actor();` is not invoking the copy constructor at all, it is invoking the default constructor instead. `Actor other = Actor();` is just compiler syntax sugar for `Actor other;` – Remy Lebeau Jul 27 '17 at 00:14

1 Answers1

1

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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
R Sahu
  • 204,454
  • 14
  • 159
  • 270