将其投射到无效*&

Cast this to void*&

本文关键字:无效      更新时间:2023-10-16

我有一个接受void*&作为参数的方法,我想将this作为参数传递。

示例:

struct A
{
    void foo()
    {
        bar((void*&)this);
    }
private:
    void bar(void*& p) {}
};

我有以下编译器错误:

cast_this.cpp: In member function 'void A::foo()':
cast_this.cpp:5:14: error: invalid cast of an rvalue expression of type 'A*' to type 'void*&'
  bar((void*&)this);
              ^

有什么方法可以投射this指针吗?

编辑:尝试bar((void* const &)this);给出:

cast_this.cpp: In member function 'void A::foo()':
cast_this.cpp:5:25: error: binding 'void* const' to reference of type 'void*&' discards qualifiers
  bar((void* const &)this);
                         ^
cast_this.cpp:8:10: note:   initializing argument 1 of 'void A::bar(void*&)'
     void bar(void*& p) {}
          ^

this是一个prvalue,它不能绑定到非常量左值引用。还有一个关于类型的问题,但值类别是一个亮点,所以我们不需要深入讨论。

你必须写这样的东西:

void *ptr = this;
bar(ptr);

函数签名void *&表明函数可能会更改其参数。对象的地址不能更改,因此这表明函数没有按照您的想法执行,或者您对函数的效果有一些误解。

正如您的问题评论中所建议的,您可以使用const限定(因为this实际上是const),但演员阵容和参数都需要它:

    bar((void* const &)this);
    void bar(void* const & p) {}

(事实上,根据下面的评论,一旦您更改了函数签名,您就不需要强制转换了)。这导致临时用this的值初始化,并绑定到barp参数(感谢M.M.的解释)。

当然,如果你可以用这种方式更改bar的签名,那么你也可以让它接受一个普通的void *

    bar(this);
    void bar(void* p) {}

或者,将指针值保存到另一个变量:

    void * t = this;
    bar(t);

注意,bar的当前签名意味着它可能会在返回之前更改t的值。