簡體   English   中英

通過類型別名實現C ++不變性

[英]C++ Immutability through a type alias

使用using聲明制作類型的不可變版本是錯誤的,可以的還是一種好的做法?

struct MutableA
{
  int i;
  float f;
};

using ImmutableA = const MutableA;

對於指針成員或ref成員,像property_const這樣的包裝器將確保Immutable對象中const安全。

這樣做的好處是將Mutable轉換為Immutable類型(我認為)是沒有成本的,並且避免了代碼重復。

這是一個好習慣嗎? 這是錯的嗎 ? 沒用嗎?

當然,它只是想使事情更具表現力。 富有表現力的代碼是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?

這里可能是更多背景信息: 不可變和const之間的區別

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM