by gpderetta · 4y ago · 0 comments
In Swift (and Kotlin and others) the compiler can prove that you never get a null pointer error at runtime. If you want something that can be null, the type is `T?` (short for `Optional<T>`) instead of `T`. Then there are various syntactically convenient ways of unwrapping it and dealing with the null case. Eg `foo ?? bar` means give me `foo` if it's not null, otherwise `bar`. Or `foo?.x` means: get the property x of foo, if foo is not null.
I haven't used C++ much in recent years. If there's an equivalent, I'd love to know about it.
E.g. in
std::string str;
str is never null, and always a valid object, because it's a value, not a pointer like in most GC'ed or dynamic languagesstd::string str1{"Apple"}; std::string str2 = std::move(str1);
Isn't str1 in an invalid (err, unspecified?) state and you shouldn't use it? It's not `null` sure, but it's not good to use.
What's better is that sanitizers don't detect this form of undefined behavior! (Clean on memory,address,undefined.)
https://godbolt.org/z/7jsxnMs8E
also relevant: https://i.imgur.com/3wlxtI0.gifv
Also, uninitialized by itself does not mean invalid though ? For your example, I wonder if it would make sense to flag it: printf could be implemented in assembly or Fortran for what we know (a few popular libc implementations are done in c++ for instance), and as such I don't know how much sense it would make for its internal usage of the pointed value to be checked against the c++ rules. I'd assume the outcome would be different with std::format or std::cout for instance
In Swift you are not allowed to declare a variable without assigning some value or nil to it before the current scope ends.
The semantics of c++ object initialization are such that a constructor will always be called.