C++朋友类 std::vector
是否可以便携地执行以下操作:
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
谢谢
,我确实有解决方法,但我很好奇这如何可能
Is it possible to do the following portably:
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>;
};
example message trying to compile above:
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
Thanks
I do have workaround, but I am curious as how this could be possible
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。
vector
(更准确地说,传递给vector
的分配器)可以将构造任务委托给自由函数或另一个类,从而使friend
>船没用。即使您传递自己的分配器,它也可能会反弹到实现内部的类。然后,您的类的构造函数可以从该类访问,而不是您的分配器。因此,如果这是您的解决方法,则不能保证。 (尽管查看 GCC 的实现,它确实谨慎地使用无反弹分配器来构造此类子对象。)
在 GCC 的 libstdc++ 中,没有 STL 容器模板在标准类或函数的范围内构造所包含的对象。
No.
vector
(more precisely, the allocator passed intovector
) can delegate the task of construction to a free function or another class, making thefriend
ship useless.Even if you pass your own allocator, it may be rebound to a class internal to the implementation. Then the constructor for your class may be accessed from that class, not your allocator. So if that's your workaround, it's not guaranteed. (Although looking at GCC's implementation, it does scrupulously use the un-rebound allocator to construct such subobjects.)
In GCC's libstdc++, no STL container template constructs the contained objects in the scope of a standard class or function.