Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear() method for resetting all class fields to their default values using *this = {} in C++

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

like image 419
mw92 Avatar asked Jan 27 '26 09:01

mw92


1 Answers

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.

like image 180
bolov Avatar answered Jan 28 '26 23:01

bolov