开发者

Is C++ guaranteed to call a certain constness of member function?

开发者 https://www.devze.com 2023-02-23 08:39 出处:网络
If I have开发者_开发技巧 the following: class A { int foo() const { j++; return i; } int& foo() {

If I have开发者_开发技巧 the following:

class A {
    int foo() const {
       j++;
       return i;
    }

    int& foo() {
       return i;
    }

    int i;
    mutable int j;
};

then obviously something like

A a;
a.foo() = 5;

calls the non-const version. But what conditions need to be met to make sure that a call is to the const or non-const version for a few examples...

int i = a.foo(); //I would expect to call the const. Is it guaranteed?

const int j = a.foo(); //Ditto

const int& l = a.foo(); //Ditto

int& k = a.foo(); //I would expect the non-const
foobar(k); //foobar is "void foobar(int)"
return; //but the compiler could potentially decide the const version is fine.


const function gets called when the object itself is const.

int i = static_cast<const A>(a).foo(); //calls const function

Also see this code for better understanding: (must read the comments)

void f(const A &a) //a is const inside the function
{
    int i = a.foo(); // calls const function
}
void h(A &a) //a is non-const inside the function
{
    int i = a.foo(); // calls non-const function
}

A a;
f(a);
h(a); //pass the same object!

See the online demo : http://ideone.com/96flE


The constness of a decides which function - what you do with the return value is not a part of overload resolution. All your samples would call the non-const version.


Return values are never considered when determining which overload to take.

Also, when a is declared as

A a;

then the non const version takes precedence.

If a is declared as

const A a;

then the const version can be called only.


Whether your member function call resolves to a const member function or not, depends on the constness of the "this" pointer i.e. the object on the LHS of dot or arrow operator that is implicitly passed to the called member function.

Resolves to non const:

A a;
a.foo();

Resolves to const:

void bar(const A& a)
{
   a.foo();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消