2017-07-27 47 views
0

我试图创建一个Actor指针指向另一个Actor对象,像这样删除:为什么的演员指针结果“的Program.exe引发断点”

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

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

Program.exe has triggered a breakpoint

但是,当我创建一个新的Actor而不是分配给ptrother参考,我可以放心地delete它没有任何错误:

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; 

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

+1

'other'位于堆栈中,并且内存不能被删除。默认'delete'实现从堆中尝试释放内存。当您尝试释放无效指针时堆管理器触发断点。 – RbMm

+0

关于三规则,“Actor other = Actor();”根本不调用复制构造函数,而是调用默认的构造函数。 '演员其他=演员();''是'演员其他'的编译器语法糖;' –

回答

1

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

您可以在一个指针调用delete,只有当它在通过向new操作的调用动态内存(即堆)被分配指向的内存。

由于other自动存储(即堆)代替,它不能与delete释放被分配的,所以你在做什么是不确定的行为

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

+0

这使得很多的意义,非常感谢你! – Hello