I need to initilise an member array of a class with a non-default constructor and without using the copy constructor.
I have the following two classes:
class MemberClass
{
public:
MemberClass(int id) { /* Do stuff */ }; // Define non-default ctor
MemberClass(const MemberClass& other) = delete; // Delete copy ctor
~MemberClass() { /* Do stuff */ }; // Overide default dtor
};
class ContainerClass
{
private:
MemberClass mem[2];
public:
ContainerClass(int id)
: mem { {id} , {id} }
{}
};
which upon compiling gives the following error:
error: use of deleted function ‘MemberClass::MemberClass(const MemberClass&)’
: mem { {id} , {id} }
but I cannot figure out a way to initialise the mem
array without defining a copy constructor. I've found answers from here and here explaining that copy-elision is occuring and a copy-ctor is needed to compile but should be removed by the compiler. The MemberClass
should never be copied, so defining a copy-ctor just for this initialisation seems very awkward and prone to more difficult debugging elsewhere.
If the MemberClass
only has a default constructor then there is no issue given by the compiler. Nor is there any issue given if mem
is not an array and is just a single MemberClass
object. My only issue is with initialising this array with the non-default ctor, and without using copy-ctor.
Weirdly, if I do not define a destructor I don't get any compilation error, which seems like a clue.
Is there a "correct" way to do this sort of initialisation?