4 ms·
However, such pointers are unsafe, since someone could pass an invalid or null pointer var/out variables are much safer, since the variable exists at the calli
by benibela 6y ago
However, such pointers are unsafe, since someone could pass an invalid or null pointer
var/out variables are much safer, since the variable exists at the calling site , is valid and not null.
It is also much safer than C++'s & references. It is very subtle, but rather amazing if you think about it. Because C++ can return a & reference, it can return a reference to a value on the stack frame of the callee, which then becomes invalid. But the var/out variable always exists on caller's site, so it is always safe.
(at least if it a reference to the stack. a reference to the heap could be freed indirectly through another reference. )
- rzzzt 6y agoI am not a heavyweight C++ user (also a very lightweight C and a, uhm... featherweight Pascal user), but I'd think using a C++ reference as a method argument should be as safe as Pascal's var parameters. Is returning references frequently done in C++? I have only seen it in ostream's << operator-like constructs where you want to chain multiple calls to the same object.
- pjmlp 6y agoNot necessarily, although it is seldom seen I the wild, you can cast a null pointer into a reference. Another source of issues might be the creation of temporaries. Yes, in index operator as well.
- benibela 6y ago>Is returning references frequently done in C++? It is rather common to avoid copying returned objects. (perhaps it becomes less common with std::move ?) For example, the [] operator on the standard collections returns a reference, so the item can be modified There Pascal has another clever idea. You can overload [] for reading and writing separately. Then x[k] := v becomes x.setItem(k, v)