Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the meaning of this[i] in c++ without overloading

Tags:

c++

This is the code from WebKit:

class ExecState : public Register 
{
 JSValue calleeAsValue() const { return this[JSStack::Callee].jsValue(); } 
 ... 
}

JSStack::Callee is const, Operator[] is not overloading in ExecState or Register,

So what's the syntax in c++ of this[JSStack::Callee] ?

like image 503
Chogri Avatar asked Oct 26 '14 14:10

Chogri


1 Answers

Well, this is a pointer to an ExecState and using the subscript operator with a pointer makes it behave as if it is an array. That is, the expression this[JSStack::Callee] accesses an object which is JSStack::Callee elements away from this. Of course, this can only possibly work if the element is a member of an array of ExecState objects.

Below is a quick stand-alone demo of using this "feature". In general I'd recommend against using it but there may be very specific needs where it is known that a type is used within an array and the accesses are viable. For example, if the type is defined locally, all known uses could be known (I'd add a comment stating that assumption, though).

#include <iostream>

class foo {
    int d_value;
public:
    foo(int i): d_value(i) {}
    int get(int i) const { return this[i].d_value; }
};

template <typename T, int Size>
int size(T(&)[Size]) { return Size; }

int main()
{
    foo f[] = { 9, 1, 8, 2, 7, 3, 6, 4, 5 };
    for (int i=0; i < size(f) - 2; ++i) {
        std::cout << "f[" << i << "].get(2)=" << f[i].get(2) << '\n';
    }
}
like image 190
Dietmar Kühl Avatar answered Oct 21 '22 19:10

Dietmar Kühl