otisonoza
otisonoza

Reputation: 1344

Cast this to void*&

I have a method which accept void*& as an argument and I'd like to pass this as a parameter.

Example:

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

I have the following compiler error:

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);
              ^

Is there any way to cast the this pointer?

EDIT: Trying with bar((void* const &)this); gives:

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) {}
          ^

Upvotes: 0

Views: 1267

Answers (2)

davmac
davmac

Reputation: 20631

As suggested in comments on your question, you can use a const qualification (because this is effectively const) - but you need it for both the cast and the parameter:

    bar((void* const &)this);

    void bar(void* const & p) {}

(And in fact, as per comment below, you don't actually need the cast once you change the function signature). This causes a temporary to be initialized with the value of this and bound to the p parameter of bar (thanks to M.M. for explanation).

Of course if you can change the signature of bar in that way then you may as well make it accept a plain void * instead:

    bar(this);

    void bar(void* p) {}

Alternatively, save the pointer value to another variable:

    void * t = this;
    bar(t);

Note that the current signature of bar implies that it might change the value of t before returning.

Upvotes: 2

M.M
M.M

Reputation: 141544

this is a prvalue, it cannot be bound to a non-const lvalue reference. There is also an issue about the type but the value category is a showstopper so we don't need to go into that.

You will have to write something like:

void *ptr = this;
bar(ptr);

The function signature being void *& suggests that the function might change its argument. The address of an object cannot be changed so this suggests that the function doesn't do what you think it does, or you have some misconception about the effect of the function.

Upvotes: 3

Related Questions