C++ friend class std::vector

做~自己de王妃 提交于 2019-12-01 23:41:33

问题


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


回答1:


No. vector (more precisely, the allocator passed into vector) can delegate the task of construction to a free function or another class, making the friendship 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.



来源:https://stackoverflow.com/questions/2907432/c-friend-class-stdvector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!