mercredi 23 décembre 2015

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?

Aucun commentaire:

Enregistrer un commentaire