Immutable classes in C++
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 deep 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.
*/
c开发者_Python百科onst 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 !
This seems like overkill. When you only have const members, the object can not be changed anyway. If you want to disallow copying, just make the copy constructor and the assignment operator private.
Looks good to me.
Marking every object const
from the factory obviates marking every data member const
, but in this example there is only one anyway.
精彩评论