我想在存储自身实例的特定类中使用 boost::ptr_map。但是,请考虑以下示例:
#include <boost/checked_delete.hpp>
#include <boost/ptr_container/ptr_map.hpp>
class foo
{
friend void boost::checked_delete<>(foo*);
~foo() {}
};
int main()
{
boost::checked_delete(new foo); // OK
boost::ptr_map<int, foo> foo_map; // error C2248: 'foo::~foo' : cannot access private member declared in class 'foo'
return 0;
}
错误发生在以下行
// verify that types are complete for increased safety
template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x; // error C2248
}
这里到底发生了什么?它不应该工作吗?我假设问题是模板是在它们包含的编译单元中定义的,并且 boost::checked_delete 是从 bosst::ptr_map 的实现源中的另一个编译单元调用的。所以,这与我作为 friend 声明的功能不同。
但是,这个问题有解决方法吗?
最佳答案
在声明 friend 时试试这个语法:
template <class T>
friend void boost::checked_delete(T*);
关于C++ 帮助 boost::ptr_map/boost::checked_delete 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6354261/