简体   繁体   English

我可以在STL容器中使用MFC对象吗?

[英]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.

相关问题 我可以使用STL容器管理不完整的类对象吗? - Can I manage incomplete class objects using STL containers? 为什么STL容器比MFC容器更受欢迎? - Why STL containers are preferred over MFC containers? 如何在STL容器中&#39;push_back&#39;大尺寸对象? - How can I 'push_back' large size objects in STL containers? 是否可以在类似STL的容器中使用WinRT对象? - Is it possible to use WinRT objects in STL-like containers? 将STL容器与Struct一起使用 - Use STL Containers with Struct 如何在C库的实现文件中使用C ++ STL容器? - How can I use C++ STL containers in the implementation file of a C library? stl 容器如何破坏对象 - How stl containers destroy objects 使用STL容器转发对象的声明 - Forward declaration of objects with STL containers 我可以使用CArchive在MFC中序列化STL的映射吗? - Can I serialize map of STL in MFC using CArchive? 如何将 scoped_allocator_adaptor 与自定义分配器(包装在一个类中)一起使用,以便它可以为某些类型而不是 STL 容器解包? - How can I use scoped_allocator_adaptor with a custom allocator (wrapped in a class) so that it can be unwrapped for some types but not STL containers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM