Initializing container of unique_ptrs from initializer list fails with GCC 4.7

前端 未结 2 1479
隐瞒了意图╮
隐瞒了意图╮ 2020-11-30 04:36

I am trying to initialise an std::vector> in a way that is equivalent to an example from Bjarne Stroustrup\'s C++11 FAQ

2条回答
  •  时光说笑
    2020-11-30 05:18

    unique_ptr's constructor is explicit. So you can't create one implicitly with from new string{"foo"}. It needs to be something like unique_ptr{ new string{"foo"} }.

    Which leads us to this

    // not good
    vector> vs {
        unique_ptr{ new string{"Doug"} },
        unique_ptr{ new string{"Adams"} }
    };
    

    However it may leak if one of the constructors fails. It's safer to use make_unique:

    // does not work
    vector> vs {
         make_unique("Doug"),
         make_unique("Adams")
    };
    

    But... initializer_lists always perform copies, and unique_ptrs are not copyable. This is something really annoying about initializer lists. You can hack around it, or fallback to initialization with calls to emplace_back.

    If you're actually managing strings with smart pointers and it's not just for the example, then you can do even better: just make a vector. The std::string already handles the resources it uses.

提交回复
热议问题