Shared pointer to an immutable type has value semantics

前端 未结 4 1089
Happy的楠姐
Happy的楠姐 2020-12-12 13:47

Sean Parent gave a talk at Going Native 2013 titled Inheritance Is The Base Class of Evil. At 20 minutes, 50 seconds in, he makes the statement that a shared pointer to an i

4条回答
  •  一整个雨季
    2020-12-12 14:20

    What he means is that they can be used to emulate value semantics.

    The main defining trait of value semantics is that two objects with the same content are the same. Integers are value types: a 5 is the same as any other 5. Compare that to reference mechanics, where objects have an identity. A list a containing [1, 2] is not the same as a list b containing [1, 2], because appending 3 to a does not have the same effect as appending 3 to b. The identity of a is different than the identity of b.

    This tends to be intuitive... it just sounds strange when put in words. Nobody makes it 3 days in C++ without getting some intuitive sense of value types vs. reference types.

    If you have a mutable value type and you want to copy it, you have to actually copy the contents of the object. This is expensive.

    The trick Sean is referring to is that if an object is immutable, then you don't have to copy the whole object, you can just refer to the old one. This is MUCH faster.

提交回复
热议问题