2

using使用声明来制作类型的不可变版本是错误的、好的还是好的做法?

struct MutableA
{
  int i;
  float f;
};

using ImmutableA = const MutableA;

对于指针或引用成员,像传播常量这样的包装器将确保不可变对象中的常量安全。

这样做的好处是将 Mutable 转换为 Immutable 类型(我认为)不会产生任何成本,并避免代码重复。

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

4

1 回答 1

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!

另一个角度是:

struct X {
     mutable int i;
};

using ImmutableX = X const;

ImmutableX x { 42 };
x.i = 666; // no problem

最后,关于:

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?

这里可能有更多背景信息:不可变和常量之间的区别

于 2017-10-03T09:45:18.800 回答