我正在尝试创建一个 Window 类,但出于某种原因,一个简单的 Window 对象定义后立即调用它的析构函数。
Window 类的 header 定义了以下构造函数和复制控件:-
Window();
Window(int);
Window(const char* title);
Window(string title);
Window(const char* title, int x, int y, int width, int height);
Window(string title, int x, int y, int width, int height);
Window(const Window &window);
Window& operator=(const Window &window);
~Window();
这些函数的关联代码如下:-
Window::Window()
{
Window(default_title, default_width, default_height, default_xpos, default_ypos);
}
Window::Window(int)
:title_(default_title),
size_({ default_width, default_height }),
position_({ default_xpos, default_ypos })
{
context_ = glutCreateWindow(title_.c_str());
setposition(position_);
setsize(size_);
glutSetWindow(context_);
}
Window::Window(string title)
:Window(title, default_width, default_height, default_xpos, default_ypos)
{ }
Window::Window(const char* title)
{
string t(title);
Window(t, default_width, default_height, default_xpos, default_ypos);
}
Window::Window(const char* title, int x, int y, int width, int height)
{
string t(title);
Window(t, width, height, x, y);
}
Window::Window(string title, int x, int y, int width, int height)
:title_(title),
size_({ width, height }),
position_({ x, y })
{
context_ = glutCreateWindow(title.c_str());
refresh();
setcallbacks();
glutSetWindow(context_);
}
Window::Window(const Window &window)
:title_(window.title_),
size_(window.size_),
position_(window.position_)
{
context_ = glutCreateWindow(title_.c_str());
refresh();
glutSetWindow(context_);
}
Window& Window::operator= (const Window &window)
{
title_ = window.title_;
size_ = window.size_;
position_ = window.position_;
context_ = window.context_;
refresh();
glutSetWindow(context_);
return *this;
}
Window::~Window()
{
glutDestroyWindow(context_);
}
上面代码中使用的其他函数(如 refresh() 和 setcallbacks())都没有直接调用类,而是调用过剩函数。如果您认为它们相关,我会将它们包括在内。
有问题的行如下所示,作为主函数的一部分调用:-
Window win("blah");
我已经尝试了几种配置,包括空构造函数、完整构造函数和赋值,但似乎都不起作用。据我所知,构造函数按预期运行并初始化所有变量,然后在它前进到主函数中的下一个语句时莫名其妙地调用析构函数。
最佳答案
这是因为你不能像这样调用构造器:
Window::Window(const char* title, int x, int y, int width, int height)
{
string t(title);
Window(t, width, height, x, y); // this create a temporary Window then destroy it
}
改为这样做:
Window::Window(const char* title, int x, int y, int width, int height)
: Window( string(t), width, height, x, y)
{}
关于c++ - 在构造函数之后立即调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24974476/