Search code examples
c++immutabilityusing-declaration

C++ Immutability through a type alias


Is it wrong, okay or a good practice to use a using declaration to make an immutable version of a type ?

struct MutableA
{
  int i;
  float f;
};

using ImmutableA = const MutableA;

For pointer or ref members a wrapper like propagate_const would insure const safety in the Immutable object.

The benefit of this would be that there would be no cost to converting the Mutable to the Immutable type (I presume), and avoid code duplication.

Is it a good practice ? Is it wrong ? Is it useless ?


Solution

  • Of course, it's just trying to make things more expressive. Expressive code is Good(TM).

    Most importantly, though, I'd note that const does not mean immutable.

    Here's a sample:

    using ImmutableString = std::string const;
    std::string s = "Hello world";
    
    ImmutableString& helloWorld = s;
    s = "Bye!";
    
    std::cout << helloWorld; // prints Bye!
    

    Another angle is:

    struct X {
         mutable int i;
    };
    
    using ImmutableX = X const;
    
    ImmutableX x { 42 };
    x.i = 666; // no problem
    

    Finally, what about:

    struct X {
         int i;
    };
    
    using ImmutableX = X const;
    
    ImmutableX* p = new ImmutableX{42};
    
    // now p->i = 666; is not OK, because it's const
    
    delete p; // whoops, not so immutable after all?
    

    Here might be more background info: Difference between immutable and const