On 1/12/26 1:29 AM, Vlad Zahorodnii wrote:
Hello,
I'd like to write a builder-like API to construct an object that
re-uses the memory at each construction stage, for example
const Point point = Point(x, y)
.scaled(scale1)
.translated(dx1, dy1)
.scaled(scale2)
.translated(dx2, dy2);
should be equivalent to writing something like
Point point(x, y);
point.scale(scale1);
point.translate(dx1, dy1);
point.scale(scale2);
point.translate(dx2, dy2);
This is primarily for personal code stylistic preferences, but it can
also sometimes lead to slightly nicer code.
However, the issue with the former API design is that it's not quite
the same as the latter design because extra Point objects are created
with it, see https://godbolt.org/z/xc5E3dbjs. Ideally, Point(x, y)
would be constructed in foo right away, and then .translated() +
.scaled() would operate with foo's memory, but it looks like it's not
the case. I'm not entirely sure if it's a GCC or a C++ restriction
(this is copy elision and move semantics but cranked to the maximum;
at quick glance, I see nothing that forbids it but I also don't see
anything that explicitly says such cases are supported) but I wonder
whether GCC doesn't see that Point(x, y) can be constructed in foo due
to the transform call chain and whether such optimizations are
possible after all.
Corrected Compiler Explorer link without
dot: https://godbolt.org/z/xc5E3dbjs