3

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

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

谢谢

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

4

1 回答 1

4

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

即使您传递自己的分配器,它也可能会被重新绑定到实现内部的类。然后可以从该类访问您的类的构造函数,而不是您的分配器。因此,如果这是您的解决方法,则不能保证。(尽管查看 GCC 的实现,它确实谨慎地使用 un-rebound 分配器来构造这样的子对象。)

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

于 2010-05-25T18:40:18.683 回答