Which constructor does std::vector call when it is making a new instance of the object it’s containing? I am under the impression it calls a default constructor but what if one is not defined or is the compiler doing that for me?
Particularly in a case as such:
class Foo
{
public:
Foo(int size)
{
data = new double[size];
}
~Foo()
{
delete[] data;
}
private:
double* data;
};
std::vector<Foo> myVector;
Foo bar(5);
myVector.push_back(bar);
//stuff
How does it know how much memory to allocate when the object has an unknown size until after construction?
At a minimum, for
std::vector<T>to compile,Tmust be copy-constructible, and copy-assignable. If you want to usestd::vector<T>::vector(int)(orstd::vector<T>::resize()), thenTmust have be default-constructible. If any of these requirements are not fulfilled, the code will not compile.…
C++03 standard, section 23.1 (discussing containers in general):
Section 20.1.4: