Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference destructing object before use

Tags:

c++

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?

like image 986
Albert Avatar asked Mar 02 '26 14:03

Albert


2 Answers

Create the object independently:

auto o = myObj();

and then use it freely:

o.someOtherOperation().someOtherOperation();
like image 184
dlask Avatar answered Mar 04 '26 03:03

dlask


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
like image 26
TartanLlama Avatar answered Mar 04 '26 02:03

TartanLlama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!