Re:Talking to C Programmers about C++ [video]
by MereInterest on Sunday September 25, 2016 @10:48AM
(#12575562)
I feel that the solution to both classes designed for heap allocation and binary libraries is the same: making a decent wrapper around them that obeys RAII. In many cases, this is just requires using `unique_ptr` with a custom deleter.
auto deleter = [](unsafe_type* t) { cleanup_unsafe(t); }
std::unique_ptr<unsafe_type, decltype(deleter)> safe(make_unsafe(), deleter);
If this is used in many places, you can make a very easy wrapper class to handle it. class safe_wrapper {
public:
safe_wrapper()
: unsafe(make_unsafe()) { }
~safe_wrapper() {
cleanup_unsafe();
}
unsafe_type* operator->() { return unsafe; }
private:
unsafe_type* unsafe;
};
(Note that the example there is only for use within a single function. If the safe_wrapper is to be returned from a function, then the copy/move operators should be defined as needed.)Certainly, when passing ownership back to the binary library, you are relying on it to correctly handle ownership. But so long as the ownership is in one's own code, you can easily add the type safety.
Regarding a stack-based class being accidentally placed on the heap, you can't prevent all errors, you can only make it less likely. I'd argue that it is easier to accidentally forget to call a cleanup function than it is to accidentally place something on the heap. With C++11 and up, any calls to "new" should be regarded with deep suspicion.
True on the FP patterns moving in, and I love them. `std::function` is a joy to work with, especially as compared to either C-style function pointers or inheritance from a "callable" type.
Re:Talking to C Programmers about C++ [video]
by qwertyuiop924 on Sunday September 25, 2016 @10:27AM
(#12575458)
Pretty much exactly the point I was trying to make about RAII. Thanks for explaining better than I did :-).
Also that no one just placed such class in the the heap, and it was missed, because no one is actually doing code reviews or making use of static analysis.
Another issue with best practices and ownership are binary libraries. There isn't any sort of control one can have over them, so they are the place where RAII and ownership just goes out of the window.
In any case this is much worse in C than C++, because at least C++ does offer some language tools to deal with it, however there is no rescue from developers using C with a C++ compiler.
> Oh, absolutely on Lisp. Lisp/Scheme are amazingly simple, and amazingly powerful. The one downside that I've found is that it doesn't correspond to the hardware as much.
Actually it can also be an upside, as you see with the adoption of FP patterns in mainstream languages, including C++.
One of the themes at CppCon was exactly hardware heterogeneity and possible C++ abstractions to take advantage of it, while keeping the algorithms high level.