Coffeehouse Post

Single Post Permalink

View Thread: A quick self-reminder why I did not pursue native development
  • User profile image
    Sven Groot

    ,androidi wrote

    Where does the safe C++ end and the C or unsafe concepts begin (as both can be in .cpp) - How can I tell which header has only C++ things in it (ignoring OS calls)? Are there things I can't do without use of C, eg. lack of libraries written this "safe/pure C++" that accomplish everything I could possibly want (in user land)?

    It's mainly about avoiding raw pointers and manual memory management. It means that pointer lifetime is managed by smart pointers like std::shared_ptr or std::unique_ptr so you won't ever write delete (and write new only to initialize a unique_ptr; initialize shared_ptr using std::make_shared). This makes your code exception-safe (resources get cleaned up regardless of what code path is taken).

    Seriously, watch Herb Sutter's video, it explains all this much better than I could in a short forum post, and touches on some other important points too.

    This idea of using scoped variables for automatic resource management doesn't just apply to smart pointers. For example, the Boost.Thread library (and as of C++11, the standard library <thread> header, available in VC11) uses this with mutex locks that ensure they get released when the lock_guard variable goes out of scope, just like the using statement in C# (but without needing a language extension).

    And for the second part of your question: sometimes you have to interact with libraries that aren't that friendly. Unfortunately, Win32 itself is written for C, not C++, so unless you use a wrapper library you may run into situations where manual resource management is unavoidable. But when you do, you can follow the pattern yourself: write a class to encapsulate the resource and clean up in its destructor. In Win32 code I've written I've used a ScopedHandle template class that was specialized for various HANDLE types and their specific deletion functions so neatly handle those.

    And std::shared_ptr and std::unique_ptr can use a custom deletion function, so it can easily be adapted for memory you got from a Win32 function that needs to be deleted using e.g. LocalFree rather than delete.