C++ Befriending boost::ptr_map / boost::checked_delete fails

C++ Befriending boost::ptr_map / boost::checked_delete fails

本文关键字:boost checked delete fails map ptr C++ Befriending      更新时间:2023-10-16

我想在存储自身实例的特定类中使用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实现源中的另一个编译单元调用的。所以,这与我作为朋友声明的函数不同。

但是,有解决这个问题的方法吗?

在声明友元时尝试以下语法:

template <class T> friend void boost::checked_delete(T*);

这是来自GCC的巨大错误消息*的开始,它是实例化链的开始(通常,在这种情况下):

在main.cpp:1:0:中包含的文件中:main.cpp:在函数"void boost::checked_delete(T*)[with T=const foo]"中:

添加

friend void boost::checked_delete<>(foo const*);

使代码可编译。

(*):13行3510个字符,270个字符/行