Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke default constructor for each element in constructed std::vector

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.

like image 949
Danra Avatar asked Jan 04 '16 09:01

Danra


People also ask

How is the default constructor invoked in C++?

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.

How do I initialize a vector to default?

The default value of a vector is 0. Syntax: // For declaring vector v1(size); // For Vector with default value 0 vector v1(5);

Does Emplace_back call constructor?

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.


2 Answers

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.

like image 75
bolov Avatar answered Sep 29 '22 07:09

bolov


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

like image 42
Humam Helfawi Avatar answered Sep 29 '22 07:09

Humam Helfawi