Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::move with vectors

I have a question about using std::move in C++.

Let's say I have the following class, which in its constructor takes a std::vector as a parameter:

class A
{
public:
    A(std::vector<char> v): v(v) {}
private:
    std::vector<char> v;
};

But if I write the following somewhere:

std::vector<char> v;
A a(v);

the copy constructor of std::vector will be called twice, right? So should I write constructor for A like the following?

class A
{
public:
    A(std::vector<char> v): v(std::move(v)) {}
private:
    std::vector<char> v;
};

And what if I would like to call the following?

std::vector<char> v;
A a(std::move(v));

Is that okay with the second version of the constructor, or should I create another constructor for A that takes std::vector<char>&&?

like image 384
Igor Avatar asked Aug 31 '26 04:08

Igor


2 Answers

Your second scheme is fine.

The vector will just be moved twice with the second version (which moves the by-value parameter into your member). If you don't mind the cost of the extra move, you can stick with just moving the by-value parameter into your member.

If you do mind, then make two constructors for different value categories of the parameter.

like image 187
StoryTeller - Unslander Monica Avatar answered Sep 01 '26 17:09

StoryTeller - Unslander Monica


Make two constructors: The first constructor should be by const&, the second as rvalue&& so it can use move semantics:

class A
{
public:
    A(const std::vector<char>& v_) : v(v_) { std::cout << "const& ctor\n"; }
    A(std::vector<char>&& v_) : v(std::move(v_)) { std::cout << "rvalue&& ctor\n"; }
private:
    std::vector<char> v;
};

Test:

int main()
{
    std::vector<char> v1{ 'a', 'b', 'c', 'd' };
    A a1(v1);
    A a2(std::vector<char>{ 1, 2, 3, 4 });
   return 0;
}

Output:

const& ctor

rvalue&& ctor

like image 29
A.S.H Avatar answered Sep 01 '26 19:09

A.S.H