开发者

Proper way to implement move semantics for class with std::vector of std::vector member

开发者 https://www.devze.com 2023-04-09 05:31 出处:网络
I have a class that has a member which is a vector of vectors. I would like to write a constructor for this class that takes an r-value reference to a single vector as an argument, and moves it into t

I have a class that has a member which is a vector of vectors. I would like to write a constructor for this class that takes an r-value reference to a single vector as an argument, and moves it into the member vector as a single element vector of the vector argument. So far I have:

class AClass
{
    std::vector<std::vector<int>> member;

public:

    AClass(std::vector<int> &&vec) : member(1) 
    {
        member[0] = std::vector<int>(std::move(vec));
    }
}

This seems to work correctly, but I am not sure if the std::move around vec is necessary. Or if the std::vector would have taken care of much of this for me had I w开发者_JS百科ritten it a little differently.


It should be shorter to write:

member[0] = std::move(vec);

in order to invoke

vector<T,Allocator>& operator=(vector<T,Allocator>&& x);

As far as I know, explicit moving is necessary, because vec is not a rvalue (it is a named variable and can be used on the left side of operator=).


The way of doing this now is to just pass the value into the constructor by value, then moving it to where you want. So

AClass(std::vector<int> vec)
{
    member.emplace_back(std::move(vec));
}

You don't need to care about whether the value is copy-constructed in, or if it was able to be moved into the constructor because it was an rvalue, or whatever. You just request, in the function definition, that you get your own copy of the item, and the language will give it to you as best it can.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号