How to declare a vector of unique_ptr's as class data member?

后端 未结 5 1286
借酒劲吻你
借酒劲吻你 2021-02-20 11:26

I\'d like to have a vector of unique_ptr\'s as a member of a class I\'m making.

class Foo {
    [...]

private:
    vector> barList;
         


        
5条回答
  •  别那么骄傲
    2021-02-20 12:09

    unique_ptr doesn't have copy semantics, so you can't use any methods that would copy the contained object. You can do this with rvalue references by using std::move in the place(s) it's trying to make a copy. Without seeing your code I can't say where that would be.

    If it compiles in the second form either you didn't exercise the same code or there's a compiler bug. Both should fail the same way.

    Your third example, storing by value is the simplest way unless your objects are large and expensive to store/copy around by value.

提交回复
热议问题