Can I use MFC objects in STL containers?

The following code does not compile for me on MSVC2005:

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

      

CMenu

- an MFC menu object (for example, a context menu). After some testing, I found out that it CMenu

doesn't have a public copy constructor.

In order 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 have lost all the benefits of using an STL container.

Do I have other options?

+2


a source to share


3 answers


You can use pointer containers or smart pointer containers for example. using shared_ptr

from Boost or TR1:



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

      

+6


a source


MFC objects are simple wrappers around Windows descriptors, and most of them are designed to release the descriptor in the destructor. It would be dangerous to have a copy constructor because of this, because the first one destroyed will invalidate the other.



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

+1


a source


You can use STL containers in conjunction with smart pointers to store pointers to heap allocated objects, which are automatically delete

d when the container is destroyed.

The correct smart pointer for this job is boost :: shared_ptr .

See also this question for more information .

0


a source







All Articles