Calling a const function rather than its non-const version

前端 未结 4 1427
深忆病人
深忆病人 2020-11-28 13:38

I tried to wrap something similar to Qt\'s shared data pointers for my purposes, and upon testing I found out that when the const function should be called, its non-const ve

相关标签:
4条回答
  • 2020-11-28 13:48

    It doesn't matter whether Data::x is a constant function or not. The operator being called belongs to container<Data> class and not Data class, and its instance is not constant, so non-constant operator is called. If there was only constant operator available or the instance of the class was constant itself, then constant operator would have been called.

    0 讨论(0)
  • 2020-11-28 13:49

    But testType is not a const object.

    Thus it will call the non const version of its members.
    If the methods have exactly the same parameters it has to make a choice on which version to call (so it uses the this parameter (the hidden one)). In this case this is not const so you get the non-const method.

    testType const test2;
    test2->x();  // This will call the const version
    

    This does not affect the call to x() as you can call a const method on a non const object.

    0 讨论(0)
  • 2020-11-28 13:59

    test is a non-const object, so the compiler finds the best match: The non-const version. You can apply constness with static_cast though: static_cast<const testType&>(test)->x();

    EDIT: As an aside, as you suspected 99.9% of the time you think you've found a compiler bug you should revisit your code as there's probably some weird quirk and the compiler is in fact following the standard.

    0 讨论(0)
  • 2020-11-28 14:08

    If you have two overloads that differ only in their const-ness, then the compiler resolves the call based on whether *this is const or not. In your example code, test is not const, so the non-const overload is called.

    If you did this:

    testType test;
    const testType &test2 = test;
    test2->x();
    

    you should see that the other overload gets called, because test2 is const.

    0 讨论(0)
提交回复
热议问题