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.
*/
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 !
At a fundamental level: immutable classes define objects which, once created, never change their value. A variable of an immutable type may only be changed by re-assigning to that variable. When we wish to only modify some portion of an immutable class, we are compelled to reassign the whole object.
Mutable and immutable are English words meaning "can change" and "cannot change" respectively. The meaning of the words is the same in the IT context; i.e. a mutable string can be changed, and. an immutable string cannot be changed.
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String class, etc. In a nutshell, immutable means unmodified or unchangeable.
In Java, when we create an object of an immutable class, we cannot change its value. For example, String is an immutable class. Hence, we cannot change the content of a string once created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With