Often I add an Empty
method to my C++ objects to clear the internal state using code similar to the following.
class Foo
{
private:
int n_;
std::string str_;
public:
Foo() : n_(1234), str_("Hello, world!")
{
}
void Empty()
{
*this = Foo();
}
};
This seems to be better than duplicating code in the constructor, but I wondered if *this = Foo()
is a common approach when wanting to clear an object? Are there any problems with this waiting to bite me on the backside? Are there any other better ways to achieve this sort of thing?
I'd let the constructor call my function instead:
class Foo
{
private:
int n_;
std::string str_;
public:
Foo()
{
Reset();
}
void Reset()
{
n_ = 1234;
str_ = "Hello, world!";
}
};
Yes, you're unnecessarily initializing the string as an empty string first, then doing an assignment, but this is much clearer.
Potential problems? How do you know that *this really is a Foo?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With