Why doesn't shared_ptr permit direct assignment

后端 未结 5 1887
闹比i
闹比i 2021-01-17 10:04

So when using shared_ptr you can write:

shared_ptr var(new Type());

I wonder why they didn\'t allow a

5条回答
  •  滥情空心
    2021-01-17 10:23

    I wonder why they didn't allow a much simpler and better...

    Your opinion will change as you become more experienced and encounter more badly written, buggy code.

    shared_ptr<>, like all standard library objects is written in such as way as to make it as difficult as possible to cause undefined behaviour (i.e. hard to find bugs that waste everyone's time and destroy our will to live).

    consider:

    #include
    
    struct Foo {};
    
    void do_something(std::shared_ptr pfoo)
    {
      // ... some things
    }
    
    int main()
    {
      auto p = std::make_shared(/* args */);
      do_something(p.get());
      p.reset();  // BOOM!
    }
    

    This code cannot compile, and that's a good thing. Because if it did, the program would exhibit undefined behaviour.

    This is because we'd be deleting the same Foo twice.

    This program will compile, and is well-formed.

    #include
    
    struct Foo {};
    
    void do_something(std::shared_ptr pfoo)
    {
      // ... some things
    }
    
    int main()
    {
      auto p = std::make_shared(/* args */);
      do_something(p);
      p.reset();  // OK
    }
    

提交回复
热议问题