Every once in a while I get hung up by this and no one has really been able to give a satisfying answer.
In a (admittedly contrived) example like this...
typedef std::string _str;
class MyClass
{
public:
MyClass(const _str &s) : m_str(s) { }
private:
const _str &m_str;
}
... Things work pretty much as expected. The member m_str
can only be assigned in the constructor initializer list and cannot be reassigned later on, and non-const iterators are unavailable. Okay, then. But if we do this instead...
typedef std::string _str;
typedef std::string &_strref;
class MyClass
{
public:
MyClass(const _strref s) : m_str(s) { }
void test() { m_str.append(std::string("why am I not const?")); }
private:
const _strref m_str;
}
... The const gets dropped. Non-cost methods may be called on m_str
and it may be reassigned, which is misleading considering it has const
written next to it.
- Can the second example be corrected to maintain const-ness?
- Where/why does the c++ spec indicate that this is correct behavior?
- What do best practices have to say on the matter?