I was using an std::optional to store a struct, and I initially went with:
std::optional<Point_t> optPosition; // declared somewhere as a class member
optPosition.emplace(..., ..., ...);
works great, but I don't really like that you have to define the constructor explicitly in the Point_t struct, and also it's not super readable (imagine if I had more members).
So I tried some alternatives:
optPosition.emplace(point_t {
.x = ...,
.y = ...,
.z = ...
});
and
optPosition = point_t {
.x = ...,
.y = ...,
.z = ...
};
I was afraid that I would be hit by some copy/move overhead, but GCC eludes them, and the generated assembly is the same in all 3 cases (GCC11).
My question is:
Is this guaranteed by the standard, or is it GCC being nice ?
If guaranteed, then in what case is emplace
useful ?
In general, besides checking the asm code, how can I know that no copy/move will be added, and when should I prefer the first case (the not-very-readable-emplace) ?