was raw-pointer constructor of shared_ptr a mistake?

前端 未结 3 1549
没有蜡笔的小新
没有蜡笔的小新 2021-02-09 02:57

In hindsight, given make_shared, would shared_ptr have a constructor that takes a raw pointer had it been introduced with C++11?

Are there stro

3条回答
  •  鱼传尺愫
    2021-02-09 03:02

    In hindsight, given make_shared, would shared_ptr have a constructor that takes a raw pointer had it been introduced with C++11?

    What if you don't control the allocation of the object? What if you need to use a custom deleter? What if you need list-initialization instead of parens?

    None of these cases is handled by make_shared.

    Additionally, if you're using weak_ptr, a shared_ptr allocated via make_shared won't free any memory until all the weak_ptrs are destroyed as well. So even if you have a normal shared pointer where none of the above apply, it's possible that you may still prefer the raw pointer constructor.

    Yet another situation would be if your type provides overloads for operator new and operator delete. These may make it ill-suited for make_shared, since those overloads will not be called - and presumably they exist for a reason.

提交回复
热议问题