[英]Can I use MFC objects in STL containers?
The following code doesn't compile for me in MSVC2005: 以下代码在MSVC2005中无法为我编译:
std::vector<CMenu> vec(10);
CMenu
is an MFC menu object (such as a context menu). CMenu
是MFC菜单对象(例如上下文菜单)。 Through some testing I learned that CMenu
does not have a public copy constructor. 通过一些测试,我了解到
CMenu
没有公共副本构造函数。
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. 当然,现在我已经失去了使用STL容器的所有好处。
Do I have any other options? 我还有其他选择吗?
You could use pointer containers or containers of smart pointers, eg using shared_ptr
from Boost or TR1: 您可以使用指针容器或智能指针容器,例如,使用Boost或TR1中的
shared_ptr
:
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. MFC对象是Windows句柄的简单包装,并且大多数对象旨在释放析构函数中的句柄。 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. 让您的容器代替手柄,并在每次需要转换回MFC-land时使用FromHandle。
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. 您可以将STL容器与智能指针结合使用,以存储指向堆分配的对象的指针,这些对象在容器被销毁时会自动
delete
。
The correct smart pointer for this work is the boost::shared_ptr . 这项工作的正确智能指针是boost :: shared_ptr 。
For more info, see also this question . 有关更多信息,请参见此问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.