指向成员的指针是非法的? [英] Pointer to member that is a reference illegal?

查看:140
本文介绍了指向成员的指针是非法的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有:

  //这在C ++ 11中都有效。 
struct Foo {
int i = 42;
int& j = i;
};

//让我们使用指向成员j的指针。
auto b =& Foo :: j; //编译器在这里不快乐
//注意,如果我试图获得一个指向成员i的指针,它会工作,如预期。
Foo f;
std :: cout<< f。* b; //尝试使用指向成员的指针

编译器抱怨说我不能取成员的地址,因为它是一个参考。确切地说:


语义问题:不能形成指向成员j的引用类型int&


我知道这样做似乎毫无意义,但我只是想知道为什么它不能做。



为什么不可能?

解决方案

成员指针只是一个偏移到结构中,而不是一个指针。只能结合结构本身(或指向结构的指针)来获取数据:将偏移量的值添加到结构的地址,并将结果取消引用以生成成员的值。 / p>

现在假设一个成员是一个引用,所以通过它访问数据已经需要一个dereference(编译器隐藏它从我们,但它需要吐出相应的指令在其输出)。如果C ++允许成员指针引用,它们将是另一种类型:需要添加到基础的偏移,然后解除引用两次。改进已经模糊的特征是太多的工作;禁止它是一个更好的出路。


Let us say I have:

// This is all valid in C++11.
struct Foo {
    int i = 42;
    int& j = i;
};

// Let's take a pointer to the member "j".
auto b = &Foo::j; // Compiler is not happy here
// Note that if I tried to get a pointer to member "i", it would work, as expected.
Foo f;
std::cout << f.*b; // Try using the pointer to member

The compiler complains that I cannot take the address of the member because it is a reference. To be precise:

Semantic Issue: Cannot form a pointer-to-member to member 'j' of reference type 'int &'

I know doing this seems pointless, but I am only wondering why it cannot be done.

Why is this impossible?

解决方案

Member pointer (as opposed to a simple pointer to a member) is simply an offset into the structure, not a pointer at all. You can get data through it only in conjunction with the structure itself (or a pointer to a structure): the value of the offset is added to the address of the structure, and the result is dereferenced to produce the value of the member.

Now suppose a member is a reference, so accessing data through it already requires a dereference (compiler hides it from us, but it needs to spit out the corresponding instructions in its output). If C++ were to allow member pointers to references, they'd be of yet another type: an offset that needs to be added to the base, and then dereferenced twice. It is too much work to improve an already obscure feature; prohibiting it is a much better way out.

这篇关于指向成员的指针是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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