开发者

value semantic tricks in C++

开发者 https://www.devze.com 2023-04-13 09:22 出处:网络
Apart from C++ (because he has operator overload), do you know anoth开发者_运维技巧er OOP language that can do (or emulate in the worst case)\"value semantics\" ?In C# if you define your \"object\" as

Apart from C++ (because he has operator overload), do you know anoth开发者_运维技巧er OOP language that can do (or emulate in the worst case) "value semantics" ?


In C# if you define your "object" as a struct it has value semantic. If you define it as a class it has reference semantic (unless you make it immutable, like string, then its semantic is more similar to the value one).

I'll add that it's quite easy to break this "implicit" semantic.

struct MyStruct
{
    public StringBuilder SB;
}

MyStruct a = new MyStruct();
a.SB = new StringBuilder();

MyStruct b = a;

now you have broken the semantic, because both a and b "point" to the same reference.


structs in D also have value semantics.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号