I'd like to create an object using a
object().addSomething().addSomethingElse()
syntax and then use it in a part of the code, but the following code won't work:
class myObj {
public:
myObj() {}
~myObj() { std::cout << "dtor called" << std::endl; }
myObj& someOtherOperation() {
return *this;
}
};
int main() {
auto& elementRef = myObj().someOtherOperation();
{
std::cout << "some stuff that uses elementRef" << std::endl;
}
}
the destructor is called before the part of the code that uses the reference.
I would like to avoid an expensive object copy operation and keeping the
object().addSomething().addSomethingElse()
syntax, but it seems references don't allow for that. Any solutions to this?
Create the object independently:
auto o = myObj();
and then use it freely:
o.someOtherOperation().someOtherOperation();
You can optimize by using move semantics when the implicit object parameter is an rvalue:
myObj someOtherOperation() & {
return *this;
}
myObj someOtherOperation() && {
return std::move(*this);
}
An example of the difference:
auto element = myObj().someOtherOperation(); //uses move semantics
myobj obj;
auto otherElement = obj.someOtherOperation(); //doesn't use move semantics
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With