gpt4 book ai didi

c++ - 防止对象过早销毁

转载 作者:太空狗 更新时间:2023-10-29 23:37:08 24 4
gpt4 key购买 nike

这是我的 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) */

但是没有更好的方法,不用求助于指针吗?也许有什么方法可以告诉堆栈暂时不要删除我的对象?

最佳答案

你违反了三原则,婊子。

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));

现在双倍免费,因为你违反了三原则。因此,请为您的类提供适当的复制构造函数/赋值运算符,或者禁止它们并正确地显式构造它。

编辑:这也解释了为什么您的指针版本工作正常 - 因为您没有调用拷贝。

关于c++ - 防止对象过早销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9673013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com