Re:A bug in GCC that may cause memory leaks in valid C++ pro...
by saghm on Thursday April 27, 2017 @07:51PM
(#14215827)
In terms of memory usage for similar Result type in C++, is there any way around allocating the space for both types (as opposed to Result in Rust, which just allocates enough space for the larger of the two)? My understanding is that there is not, although I'm still not very experienced with C++, so I wouldn't be surprised if I'm wrong
[ Parent
| on HN ]
Re:A bug in GCC that may cause memory leaks in valid C++ pro...
by vvanders on Thursday April 27, 2017 @07:57PM
(#14215866)
You can use a union + tag(which the same as Rust uses which is why they're called Tagged Unions) however you run into issues with constructors/destructors. You can do something similar with placement new/delete but it requires some hoops.
Honestly most error codes are small enough that you can just pay the hit for it on the stack and discard it once you've handled the good/bad case.
Re:A bug in GCC that may cause memory leaks in valid C++ pro...
by gpm on Thursday April 27, 2017 @08:18PM
(#14215947)
std::variant with c++17, but on linux at least you need to install gcc from git to have access to it so far.
boost::variant otherwise, but depending on the types used (if there aren't any that are nothrow default constructible) it allocates on assignment.
If you just want a result type and not a more general "rust enum", this repository does it (while only allocating space for the larger, I think) https://github.com/oktal/result/
And I don't think there's any reason you couldn't implement an equivalent of std::variant for previous versions of C++, I'm just not aware of any.
Re:A bug in GCC that may cause memory leaks in valid C++ pro...
by irishcoffee on Friday April 28, 2017 @09:38AM
(#14219226)
Heh, I implemented an in-house variant at work a week ago. As it turns out, I was able to use my variant class in a python extension I developed. Also, as it turns out, python is scary in what it lets you get away with when developing extensions.