c++boostconstructorboost-ptr-container

boost::ptr_vector constructor


I am attempting to use a boost::ptr_vector in a current project, and was wondering if it was possible to use a parameterized constructor in the push_back() method, or if I am required to use a default constructor?

As a secondary question will it still use a default constructor if I define it?


This might not be the best follow-up, but most of the implementations that I have seen with the boost::ptr_vector show that the push_back() method takes the new operator. Is it possible to create an object, and then give the pointer to that object to the push_back() method of the container?


Solution

  • For the purpose of using a ptr_vector or any ptr_container much like a standard vector, or container. it is legal to use any constructor that is desired as long as the constructor is defined (defaults will also work). The only real difference is that a ptr_container takes a pointer instead of a static object, and supports cloning which acts as a deep copy as apposed to shallow copies.

    On the follow-up. it is possible to use an existing object into the push_back() method it is:

    #include <boost/ptr_container/ptr_vector.hpp>
    #include <vector>
    typedef boost::ptr_vector<Base> thing;
    void foo(void){
        thing Bar;
        Object * newObj = new Object(param1, param2);
        bar.push_back(newObj);
    }
    

    it would seem that it attempts to use the information stored in the pointer of the object to place in the array. in that case it would be possible to give a static object. though this gives me a strange feeling when I consider giving a static object for some reason (something along the lines of a pointer container should only really be used for unique items/pointers.)