It seems that I cannot completely understand move semantics: I want to fill an std::vector (member of a class) from an external function. Currently, I have something like:
void fillVector(MyClass & myclass) {
std::vector<int> vec;
/* Filling vec */
// ...
myclass.setVector(vec);
}
class MyClass {
public:
setVector(const std::vector<int> & v) { v_ = v;}
private:
std::vector<int> v_;
};
int main() {
MyClass myclass;
fillVector(myclass);
/* Use myclass.v_ somehow */.
}
I had this code for a long time, and it works fine. Now, I cannot understand how it works since I am asigning a reference to a vector which will be destroyed. My questions are:
- How is this code able to work?
- What is the best way to implement
fillVectorandMyClass::setVector()? I think that can be done with move semantics but I cannot figure out how.
Thank you!
Aucun commentaire:
Enregistrer un commentaire