Why shared_ptr has an explicit constructor

前端 未结 5 863
挽巷
挽巷 2020-12-19 17:19

I was wondering why shared_ptr doesn\'t have an implicit constructor. The fact it doesn\'t is alluded to here: Getting a boost::shared_ptr for this

(I f

相关标签:
5条回答
  • 2020-12-19 17:21

    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.

    0 讨论(0)
  • 2020-12-19 17:27

    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).

    0 讨论(0)
  • 2020-12-19 17:31
    int main() {
    
        int foo = 5;
        fun(&foo);
    
        cout << foo << endl; // ops!!
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-19 17:37

    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.

    0 讨论(0)
  • 2020-12-19 17:46

    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
    0 讨论(0)
提交回复
热议问题