C_Arse* PainInThe() const
One thing that seems to come across quite often are classes doing things like this:
class C_SomeClass
{
public:
char* GetName() const
{
return m_pName;
}private:
char* m_pName;
};
What does this actually mean? When you think about it, it’s semantic gibberish. What you are saying here is GetName doesn’t alter the state of the class, then you’re giving back to the the client code a pointer to the raw internals of your object for them to modify as they please. Does this sound wrong to you? Good… Because it is.
Nobody would dream of writing an analogous bit of code, if it were actually legal:
const uint32_t i = 42;
uint32_t* p = &i; // Error here for obvious reasons.
*p = 10;
What should you actually do if you need to return a pointer from one of your classes’ methods? Well, you need to ask yourself about what the intention of the client would be when receiving this pointer, is the client going to dereference the pointer for the purposes of modifying the object it points to? If so, the class author should omit const from the method declaration returning the pointer. If the intention is for the client not to modify the object the declaration should take the form:
class C_SomeClass
{
public:
const char* const GetName() const
{
return m_pName;
}private:
char* m_pName;
};
The following extract from the C++ FAQ might be useful for those striving for const-correctness with respect to pointer declarations:
[18.5] What's the difference between "const Fred* p", "Fred* const p" and "const Fred* const p"?You have to read pointer declarations right-to-left.
+ const Fred* p means "p points to a Fred that is const" — that is, the Fred object can't be changed via p.
+ Fred* const p means "p is a const pointer to a Fred" — that is, you can change the Fred object via p, but you can't change the pointer p itself.
+ const Fred* const p means "p is a const pointer to a const Fred" — that is, you can't change the pointer p itself, nor can you change the Fred object via p.
Ste
Edit - Changed the example to something better after Arseny’s comments — cheers mate! That’s what I get for writing something in a rush!
![]()