Why doesn't shared_ptr permit direct assignment

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

    Why [doesn't] shared_ptr permit direct assignment [copy initialization]?

    Because it is explicit, see here and here.

    I wonder what the rationale [is] behind it? (From a comment now removed)

    TL;DR, making any constructor (or cast) explicit is to prevent it from participating in implicit conversion sequences.

    The requirement for the explicit is better illustrated with the shared_ptr<> is an argument for a function.

    void func(std::shared_ptr arg)
    {
      //...
    }
    

    And called as;

    Type a;
    func(&a);
    

    This would compile, and as written and is undesired and wrong; it won't behave as expected.

    It gets further complicated with adding user defined (implicit) conversions (casting operators) into the mix.

    struct Type {
    };
    
    struct Type2 {
      operator Type*() const { return nullptr; }
    };
    

    Then the following function (if not explicit) would compile, but offers a horrible bug...

    Type2 a;
    func(a);
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题