Reputation: 43
Ok, I will put up the code first, and then ask my question.
#include<vector>
#include<string>
using std::vector;
using std::string;
class MyStringContainer
{
public:
MyStringContainer(vector<string> strVec): _strVec(strVec){;}
MyStringContainer(MyStringContainer&& rhs): _strVec(move(rhs._strVec)){;}
private:
vector<string> _strVec;
}
int main()
{
vector<string> dummyVec(1000000, "arbitrary string");
MyStringContainer strCon1(dummyVec);
MyStringContainer strCon2(move(strCon1));
}
So I just spent some time learning move semantics, and I think I got the basic idea of it concerning how to swap raw and/or smart pointers around and setting the discarded pointers to nullptr. However when dealing with vectors (and all the containers that implement move semantics), I am not 100% sure if my code above will properly "nullptr" the pointer elements of the source vector. Does the implementation of the std::vector class already handle this for me?
Upvotes: 1
Views: 141
Reputation: 15334
The std::vector class will handle this for you. In fact in this case you could use the implicitly generated move constructor. Also if your constructor takes the vector<string>
by value, which is fine, you may want to use std::move
to move it into the member variable to save a copy:
#include<vector>
#include<string>
class MyStringContainer {
private:
std::vector<std::string> strVec_;
public:
MyStringContainer(std::vector<std::string> strVec): strVec_(std::move(strVec)){ }
};
int main()
{
std::vector<std::string> dummyVec(1000000, "arbitrary string");
MyStringContainer strCon1(std::move(dummyVec));
MyStringContainer strCon2(std::move(strCon1));
}
Note I have used std::move to move the dummyVec into the constructor as well to save another copy.
Upvotes: 1