Is there a way to create a vector of N elements without calling the copy constructor and instead calling the elements' default constructor? I do not want a copy constructor for the elements because copying should be prevented.
Here it looks like you can, option 3:
http://en.cppreference.com/w/cpp/container/vector/vector
3) Constructs the container with count default-inserted instances of T. No copies are made.
but here it looks like you cannot:
http://www.cplusplus.com/reference/vector/vector/vector/
empty container constructor (default constructor) Constructs an empty container, with no elements.
fill constructor Constructs a container with n elements. Each element is a copy of val (if provided).
range constructor Constructs a container with as many elements as the range [first,last), with each element emplace-constructed from its corresponding element in that range, in the same order.
copy constructor (and copying with allocator) Constructs a container with a copy of each of the elements in x, in the same order.
move constructor (and moving with allocator) Constructs a container that acquires the elements of x. If alloc is specified and is different from x's allocator, the elements are moved. Otherwise, no elements are constructed (their ownership is directly transferred). x is left in an unspecified but valid state.
initializer list constructor Constructs a container with a copy of each of the elements in il, in the same order.
Yes, that is how vector works.
You misread the cplusplus.com wording. It says "fill constructor Constructs a container with n elements. Each element is a copy of val (if provided)"; you can't get away from that. But you don't provide val!
We can trivially demonstrate with the following simple code that copies are not (or, at least, do not need to be) made when the elements are default-constructed:
#include <vector>
#include <iostream>
struct T
{
T() { std::cout << "def-cons\n"; }
~T() { std::cout << "dest\n"; }
T(const T&) = delete;
};
int main()
{
std::vector<T> v(5);
}
The standard itself is clear that the elements need only be default-constructible, no copyability required:
[C++11: 23.3.6.2]:explicit vector(size_type n);
- Effects: Constructs a
vectorwithnvalue-initialized elements.- Requires:
Tshall beDefaultConstructible.- Complexity: Linear in
n.
It depends on the version of C++ you're using. Before C++11, the only way to get an element into a vector was by copying:
std::vector<T> v( 10 );
was the equivalent of:
std::vector<T> v( 10, T() );
with the default constructed T copied 10 times. C++11 changed this,
and the first form is required to default construct T 10 times,
without any copying.
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