Search code examples
c++c++11copy-constructordefault-constructor

How to switch between copy-constructor and default constructor depending on argument?


I have the following code:

struct S
{
    S(): a(42) {}
    int a;
};

class P
{
public:
    P(S const *s): m_s(s ? *s : /*init m_s by default ctor - how to achieve it?*/)
private:
    S m_s;
};

I want m_s to be initialized either by copy-constructor or by default constructor, depending on pointer s:

P p1(nullptr); // expect default ctor: p1.m_s.a = 42
S s;
s.a = 84;
P p2(&s); // expect copy ctor: p2.m_s.a = 84

How can I do it in a most elegant way?


Solution

  • You could just write:

    class P {
    public:
        P(S const *s): m_s(s ? *s : S()){}
    private:
        S m_s;
    };
    

    You might find it more elegant to extract the conditional to a separate helper function:

    S createS(S const *s) {
      return s ? *s : S();
    }
    

    This may look like it will perform an unnecessary copy in the case of a nullptr argument but in practice the compiler will perform RVO and optimize out the copy.

    Live demo.