Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointers to allocated objects does not have value semantics what does it mean? [closed]

Tags:

c++

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.

like image 240
Whoami Avatar asked Apr 07 '26 18:04

Whoami


2 Answers

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).

like image 136
Jerry Coffin Avatar answered Apr 09 '26 07:04

Jerry Coffin


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 c to both a and b, we expect to be able to modify a without changing the value of b (property 3). If zap is an operation which always changes the value of its operand, we expect that b and c do not continue to be equal simply because their values were changed along with a’s, but rather because changing a’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
like image 26
TemplateRex Avatar answered Apr 09 '26 09:04

TemplateRex