what is the best and how declare const in function of c++

128 views Asked by At

I have these code

#include <iostream>
using namespace std;
class Ex;
class Exx;

class Ex {
public:
    int _val;
    int const *_p_val;
    void setPtrVal(int * const &val) {
        _p_val=val;
    }
};

class Exx {
public:
    Ex const *_ex;
    void setEx(Ex const &ex)
    {
        _ex=&ex;
    }
};

int main()
{
    Ex x;
    int i=10;
    x.setPtrVal(&i);
    Exx xx;
    xx.setEx(x);
    int y=20;
    cout<<*(xx._ex->_p_val)<<endl;
    x.setPtrVal(&y);
    cout<<*(xx._ex->_p_val)<<endl;
    cout<<*x._p_val<<endl;
    return 0;
}

1: you can see, Ex x is not a const of Ex class. And Ex const *_ex; is a pointer point to only Ex const. why everything above are ok?

2: Is const in void setEx(Ex const &ex) just means you can't modify ex in function body?

3: how fix setter function for member pointer variable if I want prototype like above (suppose for sercurity reason)?

OK. if Ex const *_ex; become Ex *_ex; So, in setter function, I want a prototype do not modify argument object, just like above. How function body become?

2

There are 2 answers

2
Mike Seymour On
  1. A pointer (or reference) to const does not have to point to a const object. It just means that it can't be used to modify the object it points to; so it can safely point to either a const or non-const object.

  2. Yes. Specifically, it means that the reference passed as the function argument can't be used to modify the object.

  3. It's better to include const if you don't need to use it for modification. That will prevent accidental modification, and allow you to point to const objects.

0
JBL On

First, you're actually right, writing void setEx(Ex const &ex) means inside setEx, the parameter &ex is cv-qualified.

That doesn't mean what's pointed at (or referenced in your case) was necessarily something already const in the calling code.

Then, onto what is the best, well it depends what you actually want. If you write Ex const* ex; for your member, it means that once it is set through your object initialization, the object itself (through its member function) cannot modify the data pointed at. It still can assign a new value to the pointer (make it point elsewhere), but that means it can't modify what's pointed at.

Finally, it comes down to what you want.

  • If the data shouldn't be modified : Ex const * ex; will enforce that.
  • If the pointer shouldn't be modified : Ex * const ex; will enforce that.
  • If both the pointer and the data must remain untouched : Ex const * const ex; will do.