I am reading the Modern C++ Design by Andrei, where it is mentioned that
"Pointers to allocated objects does not have a value semantics"
For Value semantic example, it is mentioned that 'int' is perfect. so
int x = 200, y;
y = x;
My Question?
1) What is the parameter to be considered so that i can claim that is a 'value semantic'.? 2) Why Pointers to Objects does not claimed to be 'value Semantic'.
what I understood?
If you can not copy the variable to another variable which is totally detacted from the original, then that is the 'value semantics'.
Kindly correct me if my understanding is wrong?, and also provide few simple examples.
The phrase "value semantics" is widely used, but generally rather loosely defined. I think Scott Meyers had about as good of a definition as any: "do as the ints do."
In other words, an object with value semantics is one that you can treat pretty much like an int, and if you do so, it generally won't do anything surprising. Copying, assignment, applicable operators, etc., all "just work". Each "thing" you create is independent of any others, so (for example) x + y won't change x as if you'd used x += y (which a (completely un-)fair number of string classes have done, for one example).
Stepanov gives the following definition of value semantics (which he calls a Regular Type)
T a = b; assert(a == b); // 1
T a; a = b; assert(a == b); // 2
T a = c; T b = c; a = d; assert(b == c); // 3
T a = c; T b = c; zap(a); assert(b == c && a != b); // 4
I.e., types having value semantics are DefaultConstructible, CopyConstructible, Assignable and EqualityComparible (properties 1 and 2). Furthermore,
after assigning the same value
cto bothaandb, we expect to be able to modifyawithout changing the value ofb(property 3). Ifzapis an operation which always changes the value of its operand, we expect thatbandcdo not continue to be equal simply because their values were changed along witha’s, but rather because changinga’s value did not change theirs (property 4).
Types with reference semantics can obey 1 and 2, but not 3 and 4 (i.e. modifications to one of more objects which point to or reference the same value, affect all of them).
All the built-in types obey value semantics and modifications are localized. This makes them e.g. very suited for pure functions and parallel programming. With reference semantics (e.g. of objects with virtual functions), changes are not localized anymore.
T* a = c; T* b = c; a = d; assert(b == d); // 5
T* a = c; T* b = c; zap(a); assert(b != c && a == b); // 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With