Why doesn't C++ require a “new” statement to initialize std::vector?

前端 未结 7 1224
执笔经年
执笔经年 2021-02-01 13:42
/* bar.h */
class bar{
    /* standard stuff omitted */
    std::vector foo;
};

/* bar.cpp */
bar::bar(){ 
    // foo = new std::vector();         


        
7条回答
  •  深忆病人
    2021-02-01 14:28

    Because foo is an object not a pointer.

    std::vector    // This is an object
    std::vector *  // This is a pointer to an object
                        ^^^ // Notice the extra star.
    

    New rerturns a pointer:

    new std::vector();  // returns std::vector *
    

    PS. You vector should probably contain objects not pointers.

    std::vector   foo;
    ...
    foo.push_back(my_obj());
    

    Otherwise you will need to manually delete all the objects in the vector when it goes out of scope (when the containing object is destroyed). ie if you want to keep pointers in your vector you should do one of the following:

    // 1. Manually delete all the elements in the vector when the object is destroyed.
    ~bar::bar()
    {
        for(std::vector::iterator loop = foo.begin(); loop != foo.end(); ++loop)
        {
            delete (*loop);
        }
    }
    
    // 2. Use a smart pointer:
    std::vector >  foo;
    
    // 3. Use a smart container for pointers
    boost::ptr_vector   foo
    

提交回复
热议问题