Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I have two options, one is to pass in an in-out parameter, the other is to the throw an exception.

Another one would be not using constructors at all, instead implement initialize() or create() method in the class.

> Now you have the issue that every single operation can throw an exception

Depends on the code. I tend to avoid exceptions when I can.

> you need to write code that wraps every possible resource in RAII logic.

That’s generally a good idea regardless of whether exceptions are used or not. Without RAII for file handles, next day/month/year another programmer will write `if(condition) return;` and leak the handle.

> And when it comes to implementing move and copy constructors you are left feeling like you’ve definitely done something wrong

For many classes in my code, I disable both with =delete; copy constructor. This makes a class which can be neither moved nor copied, which simplifies things substantially. For instance, if you need a RAII equivalent of CAtlFile [0] over FILE* from stdio.h, immovable file handles might be a good idea. Another thing, if the class owns many gigabytes of data in some collections, you wouldn’t want to copy anyway, too expensive. In some cases I want to move such objects, for that I define a swap() method. An explicit swap() method is IMO more readable than std::move.

For many other classes in my code, I declare no constructors at all because the default compiler-generated ones already doing what I want.

[0] https://docs.microsoft.com/en-us/cpp/atl/reference/catlfile-...



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: