Alex
Alex

Reputation: 36161

How to use a unique_ptr after passing it to a function?

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.

Upvotes: 2

Views: 211

Answers (1)

Brian Bi
Brian Bi

Reputation: 119552

If you don't want to transfer ownership of the owned object, then don't pass the unique_ptr to the function. Instead, pass a reference or a raw pointer to the function (in modern C++ style, a raw pointer is usually understood to be non-owning). In the case where you just want to read the object, a const reference is usually appropriate:

void print(const std::string&);
// ...
print(*s);

Upvotes: 7

Related Questions