0

What is the advantage of using std::move() in parametrized constructor (with initializer list) instead of regular member initialization, i.e., assign?

e.g.,

#include <iostream>
#include <vector>

template <typename V>
class myVec{
    private:
        std::vector< std::vector<V> > vec;

    public:
        myVec1(const std::vector< std::vector<V> > &myArr):vec(myArr) {};
        myVec2(const std::vector< std::vector<V> > &myArr):vec(std::move(myArr)) {};
        };

How much of an advantage (memory, performance, etc.) does one gain from using myVec1 instead of the other?

Darnoc Eloc
  • 75
  • 11
  • You will normally see this when the argument is passed by value (or r-value reference). – super Mar 01 '20 at 09:49

2 Answers2

0

In your case there will be zero changes in performance as input in both cases is const

Generally, with correct usage of move constructors the gains would be big as there wouldn't be any unnecessay copying and allocations - one for each instance of std::vector.

ALX23z
  • 4,456
  • 1
  • 11
  • 18
0

No performance difference in this case.

std::move(myArr) will produce a const rvalue reference to myArr. Now since myArr is not modifiable binding this to an rvalue reference is invalid, but it can bind to a const lvalue reference. Thus vec(std::move(myArr)) will ultimately call the copy constructor of vector.

What you want here is:

myVec(const std::vector< std::vector<V> > &myArr):vec(myArr) {}; // 1
myVec(std::vector< std::vector<V> > &&myArr):vec(std::move(myArr)) {}; // 2

Now coming back onto your original question, say you have the constructors as above. If you're using move-ctor(2), you're obviously saving on a lot of copy. Do note that here you're moving the ownership of the data from the original vector, so keep in mind your use-case.

How much of an advantage

I'll just say a LOT.

theWiseBro
  • 1,439
  • 12
  • 11
  • With your forwarding constructor design, `std::is_constructible, std::string>` is `true_type`, even though you can't construct a `myVec` from a `string`. Is there a way to fix that? – Howard Hinnant Mar 01 '20 at 15:28
  • 1
    @HowardHinnant Removed my suggestion for using perfect forwarding here. I guess we'll have to use `enable_if` or constraints here to restrict T to what can be used to construct `vec`. – theWiseBro Mar 01 '20 at 20:21
  • @HowardHinnant you may wanna go over https://stackoverflow.com/questions/39645986/constructor-using-stdforward. Awfully good explanation imo. – theWiseBro Mar 01 '20 at 20:22