From previous post, I learnt that for there are two ways, at least, to declare an array without default constructors. Like this
class Foo{
public:
Foo(int i) {}
};
Foo f[5] = {1,2,3,4,5};
Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)};
I also learnt that the first one will construct the object using the parameter directly and the second copy constructor is used here. However, when I test the code below. I make the copy constructor private. I expect to see the difference of the copy constructor usage. But it is not what I expected. Neither of the two declarations is working.
class Foo{
public:
Foo(int i) {}
private:
Foo(const Foo& f) {}
};
int main(){
Foo f[5] = {1,2,3,4,5};
Foo f[5] = {Foo(1), Foo(2), Foo(3), Foo(4), Foo(5)};
}
Can anybody explain to me why does this happen?
The first won’t construct the objects directly. It will first construct a temporary
Foo, and then copy theFoointo the element. It’s similar to your second way. The difference is that your second way won’t work with aexplicitcopy constructor, while your first will. And conversely, the first will not work with aexplicitconstructor takingint, while the second will. Stated another way, the first constructor used in the initialization of an element must not beexplicit.Notice that neither way needs to copy. But they still need to check whether the copy constructors are accessible. So, they shall behave as-if they would copy, but they don’t really need to do the copy.