C++通过类型别名的不变性

Mic*_*hel 2 c++ immutability using-declaration

使用using声明来创建类型的不可变版本是错误的,还是好的做法?

struct MutableA
{
  int i;
  float f;
};

using ImmutableA = const MutableA;
Run Code Online (Sandbox Code Playgroud)

对于指针或引用成员,像propagate_const这样的包装器将确保Immutable对象中的const安全性.

这样做的好处是将Mutable转换为Immutable类型(我推测)没有成本,并避免代码重复.

这是一个好习惯吗?这是错的吗 ?它没用吗?

seh*_*ehe 5

当然,它只是试图让事物更富有表现力.表达代码是Good(TM).

但最重要的是,我注意到这const并不意味着immutable.

这是一个示例:

using ImmutableString = std::string const;
std::string s = "Hello world";

ImmutableString& helloWorld = s;
s = "Bye!";

std::cout << helloWorld; // prints Bye!
Run Code Online (Sandbox Code Playgroud)

另一个角度是:

struct X {
     mutable int i;
};

using ImmutableX = X const;

ImmutableX x { 42 };
x.i = 666; // no problem
Run Code Online (Sandbox Code Playgroud)

最后,怎么样:

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?
Run Code Online (Sandbox Code Playgroud)

这里可能有更多背景信息:immutable和const之间的区别