views:

94

answers:

3

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?

+5  A: 

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

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

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

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

For more info, see also this question.

Matteo Italia
+1  A: 

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.

Mark Ransom
The smarter design would have been to implement them similar to `shared_ptr<>` . If you make a copy, it refers to the same menu, and that menu should be destroyed in the last destructor. gf's anwer achieves the same by wrapping CMenu in an shared_ptr instead.
MSalters
Nobody ever claimed MFC's design was smart. Do you want to take it up with Microsoft, or should I?
Mark Ransom