C ++朋友类std :: vector [英] C++ friend class std::vector

查看:80
本文介绍了C ++朋友类std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以随便执行以下操作:

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

谢谢

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

I do have workaround, but I am curious as how this could be possible

推荐答案

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

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.

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

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.)

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

In GCC's libstdc++, no STL container template constructs the contained objects in the scope of a standard class or function.

这篇关于C ++朋友类std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆