在 C++ 中使用 *this完全覆盖自实例化的类方法
下面的代码安全吗? (我已经知道它可以正确编译。)
void Tile::clear()
{
*this = Tile();
}
int main()
{
Tile mytile;
mytile.clear();
}
Is the following code safe? (I already know it compiles properly.)
void Tile::clear()
{
*this = Tile();
}
int main()
{
Tile mytile;
mytile.clear();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它可能会起作用。这取决于如何
Tile&运算符 = (const Tile&);
已实现。但是,将*this
分配给新值并没有本质上的错误。It might work. It depends on how
Tile& operator = (const Tile&);
is implemented. However, there's nothing intrinsically erroneous with assigning*this
to a new value.代码没问题,Herb Sutter 甚至建议在此调用赋值运算符,即使在构造函数中也是如此。我认为这是一个非常干净、优雅的解决方案。即使它一开始不起作用,更改代码以使其起作用也可能是一个清理问题。
The code is OK, and Herb Sutter even recommends calling the assignment operator on
this
, even within a constructor. I think that is an extremely clean, elegant solution. Even if it doesn't work at first, changing your code to make it work would probably be a matter of clean-up.这取决于实施。例如,如果赋值运算符依赖于已经初始化的类
Tile
的某个成员变量(这很常见),并且该变量在您之前没有由Tile
构造函数初始化调用*this =
赋值,您的程序可能会遇到未定义的行为。It depends on implementation. For example if the assignment operator relies on some member variable of class
Tile
being already initialized (and that is quite usual) and that variable is not initialized by theTile
constructor before you call the*this =
assignment you program might run into undefined behavior.如果您的复制构造函数没有做任何令人讨厌的事情,那么这是安全的。
Safe if your copy consturctor is not doing anything nasty.