5 ms·
So how do you protect yourself against inadvertently passing around uninitialized objects?
by realharo 10y ago
So how do you protect yourself against inadvertently passing around uninitialized objects?
- cmrdporcupine 10y agoCautioun. And the destructor has to check for initialization before cleanup.
- ryandrake 10y agoAm I the only one that finds it ironic that you have a typo in the word "Caution"? I'd be very suspicious of any failure avoidance system that relies on "user caution".
- SamReidHughes 10y agoYou'll get a run time error.
- lmm 10y agoMaybe. Or maybe you'll get an invisible resource leak, or silent data corruption, or an RCE vulnerability.
- SamReidHughes 10y agoWell I don't know about that. If you have a datatype whose constructors can't throw, it should still assert at run time about its state that it's been initialized. Like, you have to actually do that, of course. So there's more surface area for mistakes inside the object, but from the outside of the object, which is what I think this sub-thread is talking about, they get caught at run time.
- lmm 10y agoIt shouldn't have to be assertions though - you should make it correct by, well, construction. When the fields are RAII the constructor can just initialize them. If your class has different possible states and flags it's usually correct to promote the different states to differnt types (subclasses).
- SamReidHughes 10y agoI don't think we're disagreeing about anything. The scope of my comment is in reference to "So how do you protect yourself against inadvertently passing around uninitialized objects?" The answer is, with a run-time error.
- AnimalMuppet 10y agoBut all failure avoidance systems rely on user caution. Error return values have to be checked. Exceptions have to be caught and handled (correctly). RAII has to be done everywhere a resource is allocated. Now, true, some of these impose lesser burdens than others. Arguably, RAII imposes the least - but not zero. And if you forget with any resource, for that resource you are vulnerable.
- lmm 10y agoThat we can't make things perfect is no reason not to make things better. And ultimately it should be possible to enforce that all resources are managed, because ultimately all resource interfaces have to be provided by the language runtime. To a certain extent enforcing user-defined invariants is always a matter of taste, but at the same time a language that makes it easy makes people a lot better at it.
- gpderetta 10y agoExactly. Objects with an artificial invalid state are an antipattern in idiomatic c++.