3 ms·
>The correct thing is that "I didn't initialize it" won't compile Flawless detection of uninitialized reads would require solving the halting problem, which is
by xamuel 3y ago
>The correct thing is that "I didn't initialize it" won't compile
Flawless detection of uninitialized reads would require solving the halting problem, which is impossible. So requiring initialization does prevent optimal efficiency of some theoretical programs. Of course, this would only matter in cases where performance was extremely critical (and the whole point becomes moot if the alternative is to automatically zero the memory, which is even worse in this pedantic optimal-performance sense).
- tialaramex 3y agoHaving some means (as these C++ proposals all do) to explicitly say "I understand that you can't see why this is correct but it assure you it is" would be fine, and needn't be introduced to beginners at all. The problem as usual in C++ is that All The Defaults Are Wrong and because they're defaults we need to warn beginners about them. You won't write Rust's MaybeUninit<T>::assume_init() in your first program by mistake, whereas the equivalent mistake in C++ happens easily because it's the default.
- tsimionescu 3y agoThe question essentially is what the statement `T x;` should mean. Today, if T is class, it means "allocate space for a value of type T and construct it using T::T()". However, if T is a built-in type, it means "allocate space for a value of type T with no defined value", which has proven to be highly problematic in practice. The situation could be improved in two simple ways. One, you could unify the two meanings, and say that `T x;` allocates space and calls T::T() to initialize the value. The no-args constructor for built-in types already exists and initializes them to 0. Or, you could also say `T x;` is illegal syntax, one must write `T x = val;` always (or at least when T is a built-in type). In either case, an escape hatch is needed for allocating uninitialized space on the stack, since there are valid performance reasons for wanting that, in rare cases. But that should be new syntax, it really really shouldn't be the default. So you can still do something like `T x = std::uninitialized();` or whatever the syntax would be to get the current behavior in performance-critical cases, where the tradeoff makes sense. Personally, especially given C++'s use of templates that don't distinguish between built-in types and classes, I believe the first option makes the most sense, and in fact removes am ugly inconsistency from the language.