Is it possible to create a vector of pointers?

后端 未结 6 2345
情歌与酒
情歌与酒 2020-12-15 01:27

Just wondering, because of a problem I am running into, is it possible to create a vector of pointers? And if so, how? Specifically concerning using iterators and .begin()

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-15 02:03

    Yes it is possible, and in fact it is necessary to use pointers if you intend your vector to contain objects from an entire class hierarchy rather than of a single type. (Failing to use pointers will result in the dreaded problem of object slicing -- all objects are silently converted to base class type. This is not diagnosed by the compiler, and is almost certainly not what you want.)

    class c
    {
         void virtual func();
    };
    
    class sc:public c
    {
         void func(){cout<<"using func";}
    };
    
    sc cobj;
    
    vector cvect;             // Note the type is "c*"
    cvect.push_back(&cobj);       // Note the "&"
    vector::iterator citer;
    
    for(citer=cvect.begin();citer != cvect.end();citer++)   // Use "!=" not "<"
    {
         (*citer)->func();
    }
    

    Note that with a vector of pointers, you need to do your own memory management, so be very careful -- if you will be using local objects (as above), they must not fall out of scope before the container does. If you use pointers to objects created with new, you'll need to delete them manually before the container is destroyed. You should absolutely consider using smart pointers in this case, such as the smart_ptr provided by Boost.

提交回复
热议问题