5 ms·
> sizeof(std::variant<size_t, std::string>) == sizeof(size_t) + sizeof(std::string) + sizeof(discriminant) (at most 4 or 8 I'd guess?) std::variant will never
by jcelerier 9y ago
> sizeof(std::variant<size_t, std::string>) == sizeof(size_t) + sizeof(std::string) + sizeof(discriminant) (at most 4 or 8 I'd guess?)
std::variant will never allocate by itself.
- saghm 9y agoShouldn't it be `max(sizeof(size_t), sizeof(std::string)) + sizeof(discriminant)`? At least in other languages, that's how sum types work
- steveklabnik 9y agoI think both of you are also forgetting padding/alignment, though that obviously depends on the exact details.
- jcelerier 9y agofrom what I can see sizeof(std::variant<char, uint8_t>) == 2 so there is no padding between the values and the discriminant
- steveklabnik 9y agoIn this specific case, yes.
- dleslie 9y agoAnd I wasn't clear, in that I was curious about more than the union.
- jcelerier 9y agoyes, forgot the max.
- dleslie 9y agoThat's the union, but what about the algorithm?
- jcelerier 9y agowhy would it allocate ? creating objects does not trigger allocations most of the time. The only stack space used is the internal state of the functor used, which is a lot of time empty (and won't even exist anymore by the time the compiler has optimized your code). eg. look here: https://godbolt.org/g/AdLAi1 https://godbolt.org/g/AdLAi1 there's not a single new / malloc / whatever
- dleslie 9y agoNow I know that there's a stack allocation for the functor. Not all platforms have Sufficiently Smart Compilers; I've got code relying on SDCC and TCC, for instance. :) That's what I'm getting at, there's this whole new suite of functionality that is sort of opaque to me, whereas I'm used to having a grasp of what's going on at-a-glance when working with C and C++98. I'll just have to spend a weekend working with it.
- jcelerier 9y ago> Not all platforms have Sufficiently Smart Compilers; I've got code relying on SDCC and TCC, for instance. :) I'm pretty sure that it's not a matter of compiler brightness; the C and C++ standards are both pretty explicit about when the automatic and dynamic storages are used. If anything, I guess that it would be harder for compilers to allocate such things on the heap. I checked and tcc doesn't allocate anything for instance for this code; neither does gcc 4.4 in c++98 mode : int main() { struct foo { int a, b, c; char x[3000]; } f; }
- dleslie 9y agoYou're basically confirming my supposition that I'll need to spend time reviewing the new C++ standards. ;)