What happens to unique_ptr after std::move()?

Viewed 78879

This code is what I want to do:

Tony& Movie::addTony()
{
    Tony *newTony = new Tony;
    std::unique_ptr<Tony> tony(newTony);
    attachActor(std::move(tony));
    return *newTony;
}

I am wondering if I could do this instead:

Tony& Movie::addTony()
{
    std::unique_ptr<Tony> tony(new Tony);
    attachActor(std::move(tony));
    return *tony.get();
}

But will *tony.get() be the same pointer or null? I know I could verify, but what is the standard thing for it to do?

3 Answers

After move, unique_ptrs are set to nullptr. Finally, I think it depends on what attachActor is doing, however, in many cases, a good approach would be to use move semantics to guarantee single ownership for Tony at all times which is a way to reduce the risks of some types of bugs. My idea is to try to mimic ownership and borrowing from Rust.

    #include <string>
    #include <memory>
    #include <vector>
    #include <iostream>
    
    
    using namespace std;
    
    class Tony {
        public:
            string GetFullName(){
                return "Tony " + last_name_;
            }
            void SetLastName(string lastname) {
                last_name_ = lastname;
            }
        private:
            string last_name_;
    };
    
    class Movie {
        public:
            unique_ptr<Tony> MakeTony() {
                auto tony_ptr = make_unique<Tony>();
                auto attached_tony_ptr = AttachActor(move(tony_ptr));
                return attached_tony_ptr;
            }
            vector<string> GetActorsList(){
                return actors_list_;
            }
    
        private:
            unique_ptr<Tony> AttachActor(unique_ptr<Tony> tony_ptr) {
                tony_ptr->SetLastName("Garcia");
                actors_list_.push_back(tony_ptr->GetFullName());
                return tony_ptr;   // Implicit move
            }
    
            vector<string> actors_list_;
    };
    
    
    int main (int argc, char** argv) {
        auto movie = make_unique<Movie>();
        auto tony = movie->MakeTony();
        cout << "Newly added: " << tony->GetFullName() << endl;
        for(const auto& actor_name: movie->GetActorsList()) {
            cout << "Movie actors: " << actor_name << endl;
        }
    }
Related