简体   繁体   中英

Can I use MFC objects in STL containers?

The following code doesn't compile for me in MSVC2005:

std::vector<CMenu> vec(10);

CMenu is an MFC menu object (such as a context menu). Through some testing I learned that CMenu does not have a public copy constructor.

To do what I wanted to do, I needed to use a dynamic array.

CMenu* menus = new CMenu[10];
// ...
delete [] menus;

Of course, now I've lost all the benefits of using an STL container.

Do I have any other options?

You could use pointer containers or containers of smart pointers, eg using shared_ptr from Boost or TR1:

std::vector<shared_ptr<CMenu> > vec;
vec.push_back(make_shared<CMenu>());

MFC objects are simple wrappers around Windows handles, and most are designed to release the handle in the destructor. Because of that it would be dangerous to have a copy constructor, because the first one destructed will make the other one invalid.

Let your container hold the handles instead, and use FromHandle every time you need to convert back to MFC-land.

You could use STL containers in conjunction with smart pointers to store pointers to heap-allocated objects that are automatically delete d when the container is destroyed.

The correct smart pointer for this work is the boost::shared_ptr .

For more info, see also this question .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM