I have few years of commercial experience with C in embedded programming, but I am pretty new to C++, so I might be missing something in my logic.
Context:
This is possible to reset all fields of an object a to their default values by calling clear() method of class A implemented as *this = {}.
It gives exactly the same result as if using a = A();. The address of an object doesn't change using either way, so it is still the same object in case it'd be crucial for some case.
Question:
What are the real risks, drawbacks or pros of using one or the other way, especially when it comes to issues with memory usages during dynamic allocation? Or are these solutions both equivalent in all matter?
A a;
//(...)
a.clear();
/* Where: */
void A::clear()
{
*this = {};
}
instead of
A a;
//(...)
a = A();
Example:
I checked with following code:
#include <iostream>
using namespace std;
class A
{
public:
int a1{3};
int b1{0};
void clear()
{
*this = {};
}
};
int main()
{
cout << "Using a.clear():" << endl;
{
A a;
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
a.a1 = 1;
a.b1 = 2;
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
a.clear();
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
}
cout << endl << "Using a = A():" << endl;
{
A a;
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
a.a1 = 4;
a.b1 = 5;
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
a = A();
cout << a.a1 << " " << a.b1 << " address: "<< &a << endl;
}
return 0;
}
The output is:
Using a.clear():
3 0 address: 0x7ffc38d8e990
1 2 address: 0x7ffc38d8e990
3 0 address: 0x7ffc38d8e990
Using a = A():
3 0 address: 0x7ffc38d8e988
4 5 address: 0x7ffc38d8e988
3 0 address: 0x7ffc38d8e988
So as expected.
BR, MW
Yes they are semantically equivalent. And you are correct you can't change the address of an existing object.
I don't see why you would write the clear method. It's uncommon and the a = A{} or a = {} is as simple and "clear" as you can get and everybody understands what that does.
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