手动对象构造函数调用
您能否告诉我是否可以手动调用对象构造函数?我知道这是错误的,我永远不会在自己的代码中做类似的事情,并且我知道我可以通过创建和调用初始化函数来解决这个问题,但是问题是我偶然发现了一个情况,其中有数千行代码对象及其父对象的构造函数...
class MyClass()
{
MyClass() { }
virtual ~MyClass();
void reset()
{
this->~MyClass();
this->MyClass::MyClass(); //error: Invalid use of MyClass
}
};
Can you please tell me if it is possible to call object constructor manually? I know it's wrong and I would never do something like that in my own code and I know I can fix this problem by creating and calling initialization function, however the problem is that I stumbled at a case where there are thousands of lines of code in object's and its parents' constructors...
class MyClass()
{
MyClass() { }
virtual ~MyClass();
void reset()
{
this->~MyClass();
this->MyClass::MyClass(); //error: Invalid use of MyClass
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您仍然可以将构造/销毁移动到单独的函数中并直接调用它们。 IE
You can still move construction/destruction into separate functions and call those directly. i.e.
您可以使用放置新语法:
You could use placement new syntax:
使用放置 new 调用构造函数,
这会在地址处的空白空间中构造一个 MyClass。
但永远不会在课堂上内部这样做!
编辑
如果您已经拥有正确类型的对象,并且想要为其分配默认值,则另一种方法是
创建一个具有默认值的新对象,并将该值分配给现有对象。
A constructor is called using placement new
This constructs a MyClass in an empty space at address.
Would never do this inside the class though!
Edit
If you already have an object of the right type, and want to assign it default values, an alternative is
which creates a new object with default values and assigns that value to your existing object.