Is there a way to construct std::vector<C>
of N elements by invoking the default constructor for each?
The constructor from size_type
just calls C
's constructor once and then uses its copy constructor for the rest of the elements.
Constructor in C++ is a special method that is invoked automatically at the time of object creation. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. Constructor is invoked at the time of object creation.
The default value of a vector is 0. Syntax: // For declaring vector v1(size); // For Vector with default value 0 vector v1(5);
This code demonstrates that emplace_back calls the copy constructor of A for some reason to copy the first element. But if you leave copy constructor as deleted, it will use move constructor instead.
The constructor from size_type just calls C's constructor once and then uses its copy constructor for the rest of the elements.
Not true since C++11
. Look at std::vector::vector documentation:
...
vector( size_type count, const T& value, const Allocator& alloc = Allocator()); (2)
explicit vector( size_type count, const Allocator& alloc = Allocator() ); (3)
...
And then:
...
2) Constructs the container with count copies of elements with value value.
3) Constructs the container with count default-inserted instances of T. No copies are made.
...
So you need the 3rd constructor std::vector<C>(size)
It seems like this behavior exists only since c++11
.
I can't find a way of doing this before c++11
. Since no constructor can do this, the option would have been to create an empty vector, reserve and then emplace_back
elements. But emplace_back
is since c++11
so... we're back to square one.
Just do this:
std::vector<C> v(size)
Example:
#include <iostream>
#include <string>
#include <vector>
class C{
public:
C(){
std::cout << "constructor\n";
}
C(C const&){
std::cout << "copy/n";
}
};
int main()
{
std::vector<C> v(10);
}
Result: (C++11/14)
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
constructor
Results: (C++98)
constructor
copy
copy
copy
copy
copy
copy
copy
copy
copy
copy
Live Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With