下面是我的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();
}现在的问题是,在我的main函数中,对象会自行销毁(因此会调用析构函数,它会危险地free()s SDL Video Surface!)在真正的渲染开始之前。
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;
}所以我的问题是,有没有办法在程序结束之前阻止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) */但是,没有更好的方法,而不是求助于指针吗?也许可以通过某种方式告诉堆栈暂时不要删除我的对象?
发布于 2012-03-13 02:58:33
你违反了三条规则,混蛋。
pro::surface screen = SDL_SetVideoMode(320,240,16,SDL_HWSURFACE|SDL_DOUBLEBUF);等于
pro::surface screen = pro::surface(SDL_SetVideoMode(320,240,16,SDL_HWSURFACE|SDL_DOUBLEBUF));现在双倍自由,因为你违反了三的规则。所以给你的类一个合适的复制构造函数/赋值操作符,或者禁止它们并显式地正确构造它。
编辑:这也解释了为什么你的指针版本工作得很好-因为你不调用副本。
发布于 2012-03-13 02:55:11
将屏幕包装在一个特殊的包装器中,该包装器将SDL_SetVideoMode与SDL_Quit而不是SDL_FreeSurface配对。
pro::screen screen(320, 240, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
// ...然后修复你的复制工具,很明显。
https://stackoverflow.com/questions/9673013
复制相似问题