简体   繁体   中英

Using std::move() vs. assign in constructor member initializer list

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

eg,

#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?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM