C++ 帮助 boost::ptr_map/boost::checked_delete 失败

标签 c++ boost friend boost-ptr-container

我想在存储自身实例的特定类中使用 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/

相关文章:

c++ - 使用 Friend 类的构造函数

c++ - 模板名和类模板名的区别

c++ - 从字节数组中提取整数类型

c++ - boost socket读写函数线程安全吗?

c++ - 第二个 child 的 XML 路径

c++ - 尝试重载 << 流作为 friend 时无法访问的成员函数?

c++ - 模板类特化和友元类

c++ - 如何使指针的取消引用保留对该对象的引用?

c++ - 避免重复 dynamic_cast 的最佳方法?

c++ - static_cast 和 Implicit_cast 有什么区别?