Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign to *this in constructor

Tags:

c++

c++11

Suppose I have a class Foo:

class Foo {
public:
    Foo(std::string s) noexcept : bar(std::move(s)) {}

    // version 1
    Foo(int x) noexcept
    {
        // do something...
        std::string s = // ...to get a string from `x`
        *this = Foo(std::move(s));
    }

    // version 2
    Foo(int x) noexcept
        : Foo([x] {
            // do something...
            std::string s = // ...to get a string from `x`
            return Foo(std::move(s));
        }())
    {}

private:
    std::string bar;
};

Version 1 has cleaner code, but has two disadvantages: 1) if default initialization of the members is expensive, or if there are const members, this version will not work; 2) is assigning to *this in constructor safe? I have this question because I'm worried the object might be in some "incomplete" state before the constructor returns.

like image 523
Zizheng Tai Avatar asked Oct 14 '25 21:10

Zizheng Tai


2 Answers

Yes, you can do that. By the time your constructor body starts running, all the fields have been initialized and the object is valid to assign to. (Assuming your assignment operator doesn't rely on any preconditions established later in the constructor body, of course.)

like image 159
Wyzard Avatar answered Oct 17 '25 11:10

Wyzard


Keep it simple:

    Foo(int x) noexcept : Foo(getString(x)) { }

private:
    std::string getString(int x) { // make it static if possible
        // do something...
        return // ...get a string from `x`
    }
like image 22
emlai Avatar answered Oct 17 '25 10:10

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!