4 ms·
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 a
by saghm 10y ago
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
- vvanders 10y agoYou 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.
- gpm 10y agostd::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/ 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.
- irishcoffee 10y agoHeh, 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.