Was wondering if anyone could help me with this, I have this struct in my code
struct Gate {
int output[9];
};
And i had a vector of that struct, but pushing to the vector which normally would create a copy broke because its only a shallow copy, and my struct has an array
so I tried to work around this by creating a custom copy constructor.
struct Gate {
int output[9];
Gate(const Gate &old){
copy(old.output, old.output + 9, output);
}
};
but now my initializers dont work anymore, because they are trying to use this copy constructor
Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
Gate alwaysSecond{{0,1,2,0,1,2,0,1,2}};
universal_gate_finder.cpp:39:41: error: cannot convert '<brace-enclosed initializer list>' to 'const Gate&'
39 | Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
|
Does anyone know of a work around for this?
>Solution :
Gate alwaysFirst{{0,0,0,1,1,1,2,2,2}};
Gate alwaysSecond{{0,1,2,0,1,2,0,1,2}};
These lines use aggregate initialization, which is only possible on aggregates, which cannot have user-declared constructors.
By declaring a custom copy constructor, your type is not aggregate anymore.
You can replace the aggregate initialization with a std::initializer_list constructor or a constructor taking an array by reference, both of which would re-enable that syntax (more or less).
However, it is unnecessary to declare the copy constructor. The implicit copy constructor already constructs the array member from the source object by element-wise copy construction.
Your replacement instead uses copy-assignment which has no benefit over directly copy-constructing the elements.
Declaring a copy constructor also disables the implicit move constructor, which is an additional pessimization.