5 ms·
To expand on this: In C++ a useful heuristic could be to think of values like Java primitives. A C++ integer takes up some amount of space. Maybe it's four by
by repsilat 8y ago
To expand on this:
In C++ a useful heuristic could be to think of values like Java primitives.
A C++ integer takes up some amount of space. Maybe it's four bytes on your platform. Integers on your platform take up four bytes. Not "four bytes plus a pointer", but four bytes and that's it.
In those four bytes you can store 2^32 values. There's nowhere else to store whether the integer is null -- if you wanted to signal to someone that the value was "missing", you would either have to,
- Come up with your own "in-band" signal, like "-(2^31) means 'missing'", or
- Have an out-of-band signal, like a separate boolean variable, or keep a pointer to "integer or null". (Pointers being nullable is arguably kinda weird still.)
Functions that return an integer in C++ on your platform will put four bytes "in the right place" on the stack. (Or in a register? I don't really know what calling conventions look like...)
Again, there's nowhere to signal that the value is missing -- if you don't fill in that memory location or that register, well, there will just be some other (undefined) value sitting in its place that the caller will read. Ditto functions that expect integer arguments etc.
Now, this has some interesting consequences: for stack-allocated values in C++, "object identity" tends to be preserved less often than in Java. When you put an object into a `vector`, you'll probably put a copy there. When you mutate that copy or call some function on it, you're not mutating the original. You can get back to "Java semantics" of object identity and nullability etc by using pointers and explicit heap storage.
- cesarb 8y ago> Functions that return an integer in C++ on your platform will put four bytes "in the right place" on the stack. (Or in a register? I don't really know what calling conventions look like...) On a register. I don't know of any mainstream platforms which return simple values like an integer through the stack. For larger values (larger than a word or a couple of words), on the other hand, usually the calling function passes the called function a pointer to a location on the stack where it should write the result. Either way, like you said "there's nowhere to signal that the value is missing".
- kupiakos 8y agoNitpicky detail: a lot of the time, the pointer variable passed to be written to is not on the stack, e.g. using strcpy with a malloc'd buffer.
- mianos 8y agoI believe he is taking about the native retuning semantics, which is in a real register for simple types or organised to be on the stack by the caller or register frame for a larger value type. Point being, it's a compact primitive reflection of the machine, not much more.