Why shared_ptr has an explicit constructor

落爺英雄遲暮 提交于 2019-11-29 11:19:06

In this case, the shared_ptr would attempt to free your stack allocated int. You wouldn't want that, so the explicit constructor is there to make you think about it.

The logical reason is that:

  • calling the delete operator is not implicit in C++
  • the creation of any owning smart pointer (shared_whatever, scoped_whatever, ...) is really a (delayed) call to the delete operator
Alex Lim

Long time lurker, and a 3rd year soft eng student here, Haphazard guess would be, to stop you from attempting to convert a 'natural' pointer to a shared_ptr, then deallocing the pointed object, without the shared_ptr knowing about the dealloc.

(Also, reference counting problems blah blah).

user35978
int main() {

    int foo = 5;
    fun(&foo);

    cout << foo << endl; // ops!!

    return 0;
}

I think there is no reason to have explicit in this constructor.

Mentioned examples with incorrect using of offset address operator (&) make no sense since there is no place to use such operator in modern C++. Except only such idiomatic code in assignment/comparision operator as 'this == &other' and maybe some test code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!