Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emptying a C++ object

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?

like image 932
Rob Avatar asked Nov 26 '22 23:11

Rob


2 Answers

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.

like image 147
Ates Goral Avatar answered Jan 17 '23 05:01

Ates Goral


Potential problems? How do you know that *this really is a Foo?

like image 35
William Avatar answered Jan 17 '23 06:01

William