Compilation problems with vector >

前端 未结 2 1720
别那么骄傲
别那么骄傲 2020-12-19 05:48

Consider the following code:

#include 
#include 
#include 

using namespace std;

struct A
{
    int a;
    A(int         


        
相关标签:
2条回答
  • 2020-12-19 06:04

    Correct, std::auto_ptr cannot be used in std::vector.

    What the compiler is complaining about there is the assignment operator for auto_ptr changes the object being assigned from, and so it cannot be const.

    You want to use either boost::ptr_vector or a vector of boost::shared_ptrs

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

    auto_ptr has a copy constructor with a non-const parameter, so the compiler can't call it from vector::push_back() since the latter has const parameter.

    The reason is when you initialize one auto_ptr instance from another the new instance disconnects the object from the other instance and connects it to self so avoid a dangling pointer situation when one instance deletes the object and the other still holds a pointer to it.

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