简体   繁体   中英

Force compiler to choose const operator overload

I am trying to simulate a cache. When given an array, I have to determine if the operator[](size_t i) is used to get data or to set it. I've overloaded it with const in its signature for the get part and without it for the set part.

My problem is that since the array is dynamically allocated, only the non-const operator[] gets called. Eg:

    class A {    
            int n;
            double *v;
    public:
            A(int i) : n(i),v(new double[i]) {}   
            const double & operator[](int i) const {
                cout<<"get"<<endl ;
                return v[i];
            }   
            double& operator[](int i) {
                cout<<"set"<<endl;
                return v[i];
            }   
    };
    int main(){
        double pi = 3.14;
        A a(10);
        a[2] = pi;   
        pi = a[3];
    }

The result is

 set
 set

but I'm hoping to print

set
get

It doesn't have anything to do with the array being dynamically allocated. Your variable a is not const , so the non- const function will be called on it. If you had const B b(10); and did b[3] , the const version would be called.

If you really want to, you can force the const version to be called by casting to a const reference:

static_cast<const A&>(a)[3]

(Or alternatively, create a reference variable and call it on that)

You've discovered why operator[] is a poor 'interface' for cache-like operations, and also why everybody seems to be caught out by the behaviour of std::map which creates a new object if you try to 'index' one that doesn't exist.

I'd write explicit get and set methods, and that way you won't surprise users of your cache class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM