I´m starting playing around with std::unique_ptr and I just don´t want to mess up things.
On my code, I´m creating a std::unique_ptr, storing it on a vector for later use in another context and continue using the pointer:
#include <iostream> #include <string> #include <memory> #include <vector> class MyClass { public: void doWhatever () { std::cout << "Var = " << variable << std::endl; } int variable = 0; }; class Controller { public: std::vector<std::unique_ptr<MyClass>> instances; }; class OtherClass { public: void myFunction() { Controller control; std::unique_ptr<MyClass> p(new MyClass); control.instances.push_back(std::move(p)); // Continue using p. p->doWhatever(); // Is this valid ? p->variable = 10; // Is this valid ? p->doWhatever(); // Is this valid ? } }; int main() { OtherClass cl; cl.myFunction(); } The code compiles, but I´m getting segmentation fault on execution.
I imagine that calls to p after moving the pointer to the vector are invalid.... If so, what would be the solution here ? Moving to a shared_ptr ?
OBS: I cannot move to vector after using the pointer. In real application this will be running on a multi-threaded environment where one thead is using the vector data and the other continue using the original pointer p.
Thanks for helping.
std::move(p)you're not allowed to usepanymore!pitself can be (re)used,*pcan't