Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I list-initialize std::vector with perfect forwarding of the elements?

I noticed that aggregate list initalization of std::vector performs copy initialization when move is more applicable. At the same time, multiple emplace_backs do what I want.

I could only come up with this imperfect solution of writing a template function init_emplace_vector. It's only optimal for non-explicit single-value constructors, though.

template <typename T, typename... Args>
std::vector<T> init_emplace_vector(Args&&... args)
{
  std::vector<T> vec;
  vec.reserve(sizeof...(Args));  // by suggestion from user: eerorika
  (vec.emplace_back(std::forward<Args>(args)), ...);  // C++17
  return vec;
}

Question

Do I really need to use emplace_back in order to initialize std::vector as efficiently as possible?

// an integer passed to large is actually the size of the resource
std::vector<large> v_init {
  1000,  // instance of class "large" is copied
  1001,  // copied
  1002,  // copied
};

std::vector<large> v_emplaced;
v_emplaced.emplace_back(1000);  // moved
v_emplaced.emplace_back(1001);  // moved
v_emplaced.emplace_back(1002);  // moved

std::vector<large> v_init_emplace = init_emplace_vector<large>(
  1000,   // moved
  1001,   // moved
  1002    // moved
);

Output

Class large produces information about copies/moves (implementation below) and so the output of my program is:

- initializer
large copy
large copy
large copy
- emplace_back
large move
large move
large move
- init_emplace_vector
large move
large move
large move

Large class implementation

My implementation of large is simply a copyable/movable type holding a large resource that warns on copy/move.

struct large
{
  large(std::size_t size) : size(size), data(new int[size]) {}

  large(const large& rhs) : size(rhs.size), data(new int[rhs.size])
  {
    std::copy(rhs.data, rhs.data + rhs.size, data);
    std::puts("large copy");
  }

  large(large&& rhs) noexcept : size(rhs.size), data(rhs.data)
  {
    rhs.size = 0;
    rhs.data = nullptr;
    std::puts("large move");
  }

  large& operator=(large rhs) noexcept
  {
    std::swap(*this, rhs);
    return *this;
  }

  ~large() { delete[] data; }

  int* data;
  std::size_t size;
};

Edit

By using reserve, there is no copy or move. Only large::large(std::size_t) constructor is invoked. True emplace.

like image 790
reconn Avatar asked Jan 08 '20 23:01

reconn


People also ask

What is the correct way to initialize vector in?

Begin Declare v of vector type. Call push_back() function to insert values into vector v. Print “Vector elements:”. for (int a : v) print all the elements of variable a.

What is std :: Initializer_list?

std::initializer_list This type is used to access the values in a C++ initialization list, which is a list of elements of type const T .

How do you initialize a vector?

A std::vector can be initialized in several ways while declaring it: A vector can be initialized from another container in several ways: Copy construction (from another vector only), which copies data from v2:

How to create and initialize a vector in C++ STL?

Following are different ways to create and initialize a vector in C++ STL. Initializing by one by one pushing values : // CPP program to create an empty vector. // and one by one push values. #include <bits/stdc++.h>. using namespace std; int main()

How to move elements into a vector after it is constructed?

Iterator move-construction, using std::make_move_iterator, which moves elements into v: With the help of the assign () member function, a std::vector can be reinitialized after its construction:

What is perfect forwarding in C++?

Today, we solve " ... a herefore unsolved problem in C++" (Bjarne Stroustrup). To make the long story short, I will write about perfect forwarding. But, what is perfect forwarding? If a function templates forward its arguments without changing its lvalue or rvalue characteristics, we call it perfect forwarding. Great.


1 Answers

Can I aggregate-initialize std::vector ...

No. std::vector is not an aggregate, so it cannot be aggregate-initialised.

You may mean list-initialisation instead, in which case:

Can I [list-initialise] std::vector with perfect forwarding of the elements?

No. List-initialisation uses the std::initializer_list constructor and std::initializer_list copies its arguments.

Your init_emplace_vector appears to be a decent solution, although it can be improved by reserving the memory before emplacing the elements.

like image 84
eerorika Avatar answered Oct 25 '22 19:10

eerorika