简体   繁体   中英

How can a C++ compiler detect a non-const function body?

Having stumbled over the following piece of code:

class Person
{
private:
    char name[10];
public:
    // this won't compile:
    char* getName_1() const {
        return name;
    }
    // this will: 
    const char* getName_2() const {
        return name;
    }
};

I am wondering exactly how a compiler can tell that getName_1() is not a const function. Because there is no piece of code inside the function body that is actually modifying a member variable.

Since getName_1 is marked as const all fields of this class are treated as const.

So type of name in getName_1 is const char[10] .

This can't be converted implicitly to char * (return type), so compiler reports an error.

getName_1() is a const method, as it is literally marked as const in its declaration. That means its implicit this pointer is const , so the name member is treated as const , and so getName_1() can't return a non-const pointer to const data, which is why it won't compile.

As an addition to other (correct) answers, this compiles:

class Person
{
private:
    char* name;
public:
    // this compiles:
    char* getName_1() const {
        return name;
    }
};

More than anything, this shows that contrary to popular myth, array in C++ is not a pointer.

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