简体   繁体   中英

Returning non-const reference from a const member function

Why does returning the reference to a pointed-to member variable work, but not the other? I know that a const member function should only return const references, but why does that not seem true for pointers?

class MyClass
{
  private:
    int * a;
    int b;
  public:
    MyClass() { a = new int; }
    ~MyClass() { delete a; }

    int & geta(void) const { return *a; } // good?
    int & getb(void) const { return b; }  // obviously bad
};

int main(void)
{
  MyClass m;

  m.geta() = 5;  //works????
  m.getb() = 7;  //doesn't compile

  return 0;
}
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; }  // obviously bad

In a const-function, every data member becomes const in such way that it cannot be modified . int becomes const int , int * becomes int * const , and so on.

Since the type of a in your first function becomes int * const , as opposed to const int * , so you can change the data (which is modifiable):

  m.geta() = 5;  //works, as the data is modifiable

Difference between : const int* and int * const .

  • const int* means the pointer is non-const , but the data the pointer points to is const .
  • int * const means the pointer is const , but the data the pointer points to is non-const .

Your second function tries to return const int & , since the type of b become const int . But you've mentioned the actual return type in your code as int & , so this function would not even compile (see this ), irrespective of what you do in main() , because the return type doesn't match. Here is the fix:

 const int & getb(void) const { return b; }  

Now it compiles fine! .

Because a becomes int * const a; . That is, you cannot change the value of a (change what it points at), just as const says. The const-ness of what a points at is a completely different issue.

Please see my answer here for a thorough discussion of const and const member functions.

Nawaz's answer is very good. However, the point about the compiler catching the error need not always hold. The C++ FAQ warns about it here .

The good news is that the compiler will often catch you if you get this wrong. In particular, if you accidentally return a member of your this object by non-const reference [...] the compiler will often detect it and give you a compile-time error [...].

The bad news is that the compiler won't always catch you: there are some cases where the compiler simply won't ever give you a compile-time error message.

Translation: you need to think. If that scares you, find another line of work; “think” is not a four-letter word.

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