C++朋友类 std::vector

发布于 2024-09-03 06:50:57 字数 623 浏览 2 评论 0原文

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

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

尸血腥色 2024-09-10 06:50:57

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文