C ++的朋友类std :: vector

时间:2010-05-25 18:34:22

标签: c++ stl friend

是否可以便携式执行以下操作:

struct structure {
    structure() {}
private:
    // only allow container copy construct
    structure(const structure&) {}
    // in general, does not work because allocator (not vector) calls copy construct
    friend class std::vector<structure>;
};

尝试编译上面的示例消息:

In member function void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) 
[with _Tp = kernel_data<const double*>::block]:
...
/usr/include/c++/4.3/ext/new_allocator.h:108: error: within this context

由于

我确实有解决方法,但我很好奇这是怎么可能的

1 个答案:

答案 0 :(得分:4)

没有。 vector(更确切地说,传递给vector的分配器)可以将构造任务委托给自由函数或其他类,使friend船无用。

即使您传递了自己的分配器,它也可能会反弹到实现内部的类。然后可以从该类访问您的类的构造函数,而不是您的分配器。所以如果这是你的解决方法,那就不能保证了。 (虽然看看GCC的实现,但是它确实使用了不反弹的分配器来构建这样的子对象。)

在GCC的libstdc ++中,没有STL容器模板在标准类或函数的范围内构造包含的对象。

相关问题