And how can I write my own array class to not need a default constructor for its elements? Right now, when I do the new [] to allocate space, I need a default constructor.
std::vector does not.
How do they do this magic?
And how can I write my own array class to not need a default constructor for its elements? Right now, when I do the new [] to allocate space, I need a default constructor.
std::vector does not.
How do they do this magic?
I think, there will always be a default constructor, if the source code does not have it, the compiler will write it under the hood.
You could allocate a block of bytes, then use placement new
to make new instance of T
(your parametric type) via copy constructor (not default constructor of course) when new items are pushed to the vector's back. This will not allow to to make "a vector of N default-initialized Ts" (which std::vector can make - which is why it does need T to have a default constructor for this purpose), but you could make vectors that start empty and can have Ts pushed onto them.
std::vector
doesn't need the default constructor because it never uses it. Every time it needs to construct an element, it does it by using the copy constructor, because every time it has something to copy: either existing vector element or an element you yourself supplied for copying (explicitly or implicitly, by relying on a default argument)
You can write a class like that in exactly the same way: every time you need to construct a new element in your array, require the user to supply an element for copying. In this case constructing that original element becomes user's responsibility.
Every time it appears as if std::vector
"requires" a default constructor from you, it simply means that somewhere you relied on a default argument of some of the vector
s methods, i.e. it was you who tried to default-construct an element, not the vector. The vector itself, again, will never try to default-construct elements.
std::vector
only requires the element to have a default constructor if you use it in a way which requires the default constructor. So this code (stolen from a deleted answer) won't compile, because X
does not have a default ctor:
#include <vector>
struct X
{
X(int) {}
};
int main(void)
{
std::vector<X> x(1); // vector of length 1, second argument defaults to X() !!
return 0;
}
But if you write main
like this instead:
int main(void)
{
std::vector<X> x; // make empty vector
x.push_back(X(1));
return 0;
}
Then it works fine.