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.
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.)
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`
}
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