C++与 boost::ptr_map / boost::checked_delete 交友失败
我想在存储自身实例的特定类中使用 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 的实现源中的另一个编译单元调用的。所以,这与我作为朋友声明的功能不同。
但是,有解决这个问题的方法吗?
I want to use a boost::ptr_map inside a specific class which stores instances of itself. However, please consider the following example:
#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;
}
The error happens at the following line
// 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
}
What exactly is going on here? Shouldn't it work? I assume that the problem is that templates are defined in the compilation unit they are included in and boost::checked_delete is called from another compilation unit in the implementation source of bosst::ptr_map. So, it's not the same function I declared as a friend.
However, is there a workaround for this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
声明友元时尝试以下语法:
模板
朋友无效升压::checked_delete(T*);
Try this syntax when declaring the friend:
template <class T>
friend void boost::checked_delete(T*);
这是来自 GCC 的巨大错误消息*的开始,这是实例化链的开始(通常,在本例中):
添加
使代码编译。
(*):13 行和 3510 个字符,每行 270 个字符
Here is the start of the huge error message* from GCC, which is the start of the chain of instantiations (usually, and in this case):
Adding
makes the code compile.
(*): 13 lines and 3510 characters for 270 chars/line