3 ms·
The key to RAII is not so much constructors as destructors. If you want to be able to signal construction failure you just have an init() member function that r
by fluoridation 4y ago
The key to RAII is not so much constructors as destructors. If you want to be able to signal construction failure you just have an init() member function that returns a bool or some integer. As for dynamic allocation, when I worked on driver development for Windows, I just had an allocate<T>() function that returned a properly constructed std::unique_ptr<T> with the deallocation function properly set and with the T fully constructed (you may need more than one allocation function if you need to allocate from multiple contexts that require allocation in slightly different ways).
>Not to mention, RAII makes it impossible to check whether you successfully released the resource
Actually, RAII makes it much easier by encoding that knowledge into the owning object. Using the example above, you could call allocate<T, do_something_special_on_deallocation_failure>(). Then whenever the pointer goes out of scope you'll do the special thing without the user of the object having to know what that special thing is.
- tsimionescu 4y agoAll of this complicates the program significantly, and greatly reduces the advantages of RAII. If you're not using the constructors for initialization, than your desturctors also have to handle the case where the objects didn't even attempt to acquire the resource they may represent, for example. Also, how to handle a failure to release a resource is context dependent, you can't encode it in the type of the resource unless you create a different type for each call site.
- fluoridation 4y agoIf you really need to do something different at each release point then you can have do_something_special_on_deallocation_failure() notify the error to the release point by a number of different mechanisms. Yes, all of this makes the code more complicated. The point of these features is not to make the code simpler, but to make it more robust. Rust is also more complicated than C.
- germandiago 4y agoYes, without exceptions is more involved, but way easier than any C alternative doing couple-of-functions mstching for alloc/dealloc.