There are three ways I know of to create an immutable object.
Method 1: internally immutable class members, internally and externally unmodifiable.
#ifndef INTERNALLY_IMMUTABLE_HPP
#define INTERNALLY_IMMUTABLE_HPP
#include <string>
class internally_immutable
{
public:
internally_immutable(const std::string & str)
: str_(str)
{
}
std::string get_str() const
{
return str_;
}
private:
const std::string str_;
};
#endif
Method 2: externally immutable class members, externally unmodifiable.
#ifndef EXTERNALLY_IMMUTABLE_HPP
#define EXTERNALLY_IMMUTABLE_HPP
#include <string>
#include <vector>
class externally_immutable
{
public:
externally_immutable(const std::string & str)
: str_(str)
{
}
std::string get_str() const
{
return str_;
}
private:
std::string str_;
};
#endif
Method 3: type immutable, partially externally unmodifiable, as someone could bypass your typedef.
#ifndef TYPED_IMMUTABLE_HPP
#define TYPED_IMMUTABLE_HPP
#include <string>
#include <vector>
typedef const typed_mutable typed_immutable;
class typed_mutable
{
public:
typed_mutable(const std::string & str)
: str_(str),
vec_()
{
}
void set_str(const std::string & str)
{
str_ = str;
}
std::string get_str() const
{
return str_;
}
private:
std::string str_;
};
#endif
What are the pros and cons of each immutable type? Compiler optimizations, impediments, usage of each type... Are there other ways of creating immutable objects in C++? What is the recommended, or most common way to create these immutable classes in C++?