Re:Recommendations about coding in C++
by msbarnett on Sunday February 19, 2017 @02:33PM
(#13681462)
You'd think. But there was a long argument here[1] not even a week ago with multiple people passionately asserting that they were entitled to be able to rely on completely predictable and non-fatal semantics when derefrencing a null pointer.
Re:Recommendations about coding in C++
by catnaroek on Sunday February 19, 2017 @03:16PM
(#13681733)
The problem with C and C++ isn't so much that undefined behavior exists, but the fact that the rules that determine when a program has defined behavior aren't formalized rigorously enough. The C and C++ specifications are written in natural language, which always leaves room for ambiguity, no matter how pedantically one tries to write.
If you want to convince a single other person that a C program you have written has no undefined behavior, then you and that person have to hopefully interpret English the same way. It would be completely hopeless to try to convince a hundred people that a nontrivial C program has no undefined behavior. And successful programs typically have way more than a hundred users.
The phasing was chosen to be provocative and attention grabbing (because, yeah, duh). The content of the point, however, is about avoiding undefined behavior, period, and not just lazily assuming "it works" means "it will always work".
Re:Recommendations about coding in C++
by catnaroek on Sunday February 19, 2017 @02:29PM
(#13681437)
If a programmer needs to reminded of this, they have no business programming.
This used to compile and work just fine years ago (perhaps relying on undefined behavior):
static void takes_null_reference_by_default(int& p = *((int*) nullptr)) {
if (&p) ++p;
}
int main(int argc, char* argv[]) {
int v1 = 15;
int v2 = 25;
takes_null_reference_by_default(v1);
takes_null_reference_by_default();
takes_null_reference_by_default(*((int*) nullptr));
takes_null_reference_by_default(v2);
std::cout << v1 << " " << v2 << std::endl;
}
Now g++ complains with: junk.cpp:5:10: warning: reference cannot be bound to dereferenced null pointer in well-defined C++ code; pointer may be assumed to always convert to true
[-Wundefined-bool-conversion]./a.out still runs though. And the de-references are just pseudo-de-references, it never "really" happens.
EDIT: also mentioning the fits "delete this;" gave some people, but worked very well in the ACE Networking Library and various other places.
"delete this" was obsolete around 20 years ago. It was considered valid C++ in the very early days, but that was a long time ago.
Something's wrong with us if this has to be mentioned in a list like this.