I'm trying to get my head around shared pointers at the moment and how they work. I would be really grateful for any advice you could give on the below.
Please could you advise on:
When to use std::move in make_shared
What the shared pointer points to if it is constructed using make_shared on an object which is constructed using emplace_back and some user input and that object then disappears from scope e.g. in a for loop I write,
vector_declared_outside_for_loop.emplace_back(std::make_shared(object(std::string user_input)))
, what happens to the shared_ptr in the for loop after the for loop ends?
- If I now make a vector of pairs of the shared_ptrs from vector_declared_outside_for_loop and some other variable such as int number_input in a subsequent for loop eg.
std::vector<std::pair<shared_ptr<object>, int>> new_vector;
for(int i{0}; i<.size(); ++i){
new_vector.push_back(std::make_pair(shared_ptr<object> vector_declared_outside_for_loop [i], int connection_type));
}
Do the shared_ptrs in new_vector point to anything? Or am I just pushing new_vector back?
shared_ptras "pointing to" an object, think of it as being an object that can be shared. It behaves exactly like any other C++ object.make_shared<T>(arguments)is almost the same asshared_ptr<T>(new T(arguments)), but safer and ore efficient.