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

后端 未结 3 1777
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-03 19:43

This code is what I want to do:

Tony& Movie::addTony()
{
    Tony *newTony = new Tony;
    std::unique_ptr tony(newTony);
    attachActor(std::m         


        
3条回答
  •  离开以前
    2021-02-03 19:58

    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 
        #include 
        #include 
        #include 
        
        
        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 MakeTony() {
                    auto tony_ptr = make_unique();
                    auto attached_tony_ptr = AttachActor(move(tony_ptr));
                    return attached_tony_ptr;
                }
                vector GetActorsList(){
                    return actors_list_;
                }
        
            private:
                unique_ptr AttachActor(unique_ptr tony_ptr) {
                    tony_ptr->SetLastName("Garcia");
                    actors_list_.push_back(tony_ptr->GetFullName());
                    return tony_ptr;   // Implicit move
                }
        
                vector actors_list_;
        };
        
        
        int main (int argc, char** argv) {
            auto movie = make_unique();
            auto tony = movie->MakeTony();
            cout << "Newly added: " << tony->GetFullName() << endl;
            for(const auto& actor_name: movie->GetActorsList()) {
                cout << "Movie actors: " << actor_name << endl;
            }
        }
    

提交回复
热议问题