App*_*ker 2 c++ oop destructor memory-management
这是我pro::surface班级的(相关)代码:
/** Wraps up SDL_Surface* **/
class surface
{
SDL_Surface* _surf;
public:
/** Constructor.
** @param surf an SDL_Surface pointer.
**/
surface(SDL_Surface*);
/** Overloaded = operator. **/
void operator = (SDL_Surface*);
/** calls SDL_FreeSurface(). **/
void free();
/** destructor. Also free()s the internal SDL_Surface. **/
virtual ~surface();
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,在我的main函数中,对象会free()在真正的渲染开始之前破坏自身(并因此调用危险的SDL视频表面的析构函数!).
int main(int argc, char** argv)
{
...
// declared here
pro::surface screen = SDL_SetVideoMode(320,240,16,SDL_HWSURFACE|SDL_DOUBLEBUF);
// event-handling done here, but the Video Surface is already freed!
while(!done) { ... } // note that "screen" is not used in this loop.
// hence, runtime error here. SDL_Quit() tries to free() the Video Surface again.
SDL_Quit();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,有没有办法阻止pro::surface实例在程序结束前销毁自己?手动执行内存管理有效:
/* this works, since I control the destruction of the object */
pro::surface* screen = new pro::surface( SDL_SetVideoMode(..) );
/* it destroys itself only when **I** tell it to! Muhahaha! */
delete screen;
/* ^ but this solution uses pointer (ewww! I hate pointers) */
Run Code Online (Sandbox Code Playgroud)
但是,如果不诉诸指针,是不是有更好的方法?也许某种方式告诉堆栈不要删除我的对象呢?
你违反了三法则,婊子.
pro::surface screen = SDL_SetVideoMode(320,240,16,SDL_HWSURFACE|SDL_DOUBLEBUF);
Run Code Online (Sandbox Code Playgroud)
等于
pro::surface screen = pro::surface(SDL_SetVideoMode(320,240,16,SDL_HWSURFACE|SDL_DOUBLEBUF));
Run Code Online (Sandbox Code Playgroud)
现在双倍自由,因为你违反了三法则.因此,为您的类提供适当的复制构造函数/赋值运算符,或者禁止它们并正确地构造它.
编辑:这也解释了为什么你的指针版本工作正常 - 因为你没有调用副本.