I just started learning the new C++ memory model:
#include <string>
#include <iostream>
#include <memory>
void print(unique_ptr<std::string> s) {
std::cout << *s << " " << s->size() << "\n";
}
int main() {
auto s = std::make_unique<std::string>("Hello");
print(std::move(s));
std::cout << *s;
return 0;
}
Right now calling cout << *s; results in a segfault, as it should. I understand why it happens. But I also would like to know if there's a way get back the ownership. I'd like to be able to use a value after passing it to a function.
std::moveit, then you are giving it away. If you want to keep it, then don't usestd::move. Pass by reference.s,std::movemay not be the best way. Take a look atunique_ptr's methods in the documentationunique_ptr<string>as an argument means: i'll transfer you this string. This is hardly what you want as an argument of a function. You should not useunique_ptrfor arguments unless really needed. b) Use a reference, and if you're not modifying it, a const reference.const string&means: i'll pass you a string that exists (references can't be null, no null check needed) and it's mine (ownership remains on the caller) and you shouldn't modify it.string&means: it's mine, but you can touch. c) Standard pointer when it can be null (i.e. optional parameters).