Why doesn't shared_ptr permit direct assignment

后端 未结 5 1923
闹比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:20

    The syntax:

    shared_ptr var = new Type();
    

    Is copy initialization. This is the type of initialization used for function arguments.

    If it were allowed, you could accidentally pass a plain pointer to a function taking a smart pointer. Moreover, if during maintenance, someone changed void foo(P*) to void foo(std::shared_ptr

    ) that would compile just as fine, resulting in undefined behaviour.

    Since this operation is essentially taking an ownership of a plain pointer this operation has to be done explicitly. This is why the shared_ptr constructor that takes a plain pointer is made explicit - to avoid accidental implicit conversions.


    The safer and more efficient alternative is:

    auto var = std::make_shared();
    

提交回复
热议问题