Immutable classes in C++
- by ereOn
Hi,
In one of my projects, I have some classes that represent entities that cannot change once created, aka. immutable classes.
Example : A class RSAKey that represent a RSA key which only has const methods. There is no point changing the existing instance: if you need another one, you just create one.
My objects sometimes are heavy and I enforced the use of smart pointers to avoid copy.
So far, I have the following pattern for my classes:
class RSAKey : public boost::noncopyable, public boost::enable_shared_from_this<RSAKey>
{
public:
/**
* \brief Some factory.
* \param member A member value.
* \return An instance.
*/
static boost::shared_ptr<const RSAKey> createFromMember(int member);
/**
* \brief Get a member.
* \return The member.
*/
int getMember() const;
private:
/**
* \brief Constructor.
* \param member A member.
*/
RSAKey(int member);
/**
* \brief Member.
*/
const int m_member;
};
So you can only get a pointer (well, a smart pointer) to a const RSAKey. To me, it makes sense, because having a non-const reference to the instance is useless (it only has const methods).
Do you guys see any issue regarding this pattern ? Are immutable classes something common in C++ or did I just created a monster ?
Thank you for your advices !