#include <iostream>
#include <string>
#include <cassert>
struct Foo
{
std::string bar = "standard";
int x = 1;
int y = 1;
bool operator==(const Foo&) const = default;
bool operator!=(const Foo&) const = default;
void ResetToStandard()
{
bar = "standard";
x = 1;
y = 1;
}
};
int main(int argc, char* argv[])
{
Foo f, g;
g.bar = "Hello world!";
g.x = 123;
g.y = 234;
g.ResetToStandard();
assert(f == g);
}
In this sample code (very simplified real world code) I have a struct Foo
whose fields have default values. There is also a ResetToStandard
function that sets all field to their standard value, but all the values are repeated in this function.
Then I came up with this, which works fine.
void ResetToStandard()
{
*this = Foo();
}
Is this pattern common? Is this the idiomatic way?
I would use *this = {}
like this (to reassign this
from default constructed object).
Which should use the move constructor.
#include <iostream>
#include <string>
#include <cassert>
struct Foo
{
std::string bar = "standard";
int x = 1;
int y = 1;
bool operator==(const Foo&) const = default;
bool operator!=(const Foo&) const = default;
void ResetToStandard()
{
*this = {};
}
};
int main(int argc, char* argv[])
{
Foo f, g;
g.bar = "Hello world!";
g.x = 123;
g.y = 234;
g.ResetToStandard();
assert(f == g);
}
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