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

后端 未结 5 1285
借酒劲吻你
借酒劲吻你 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 11:56

    Often a std::move(iUniquePtr) is missing somewhere (e. g. when using push_back).

    0 讨论(0)
  • 2021-02-20 11:59

    An excerpts from www.cplusplus.com

    std::unique_ptr::operator=
    

    unique_ptr assignment The object acquires the ownership of x's content, including both the stored pointer and the stored deleter (along with the responsibility of deleting the object at some point). Any object owned by the unique_ptr object before the call is deleted (as if unique_ptr's destructor was called).

    But there is a warning too:

    This page describes a feature introduced by the latest revision of the C++ standard (2011). Older compilers may not support it.

    MSVC 2010 defines operator= as private (non-copyable) but supports swap method.

    0 讨论(0)
  • 2021-02-20 12:01

    You can't use unique_ptr in vector because vector implementation strongly relies on values assign operator, which is private in unique_ptr. Use shared_ptr from boost or other smart ptr implementation from C++11.

    0 讨论(0)
  • 2021-02-20 12:09

    The problem here is that somewhere, your code is attempting to call the "copy-assignment" operator of Foo.

    This causes the compiler to attempt to generate a copy-assignment operator which calls the copy-assignment operators of all the subobjects of Foo. Eventually, this leads to an attempt to copy a unique_ptr, an operation which is not possible.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题