Understanding the warning: binding r-value to l-value reference

后端 未结 2 1957
走了就别回头了
走了就别回头了 2020-12-16 19:05

I want to pass a struct by reference so it won\'t be copied, but Resharper is giving the warning below:

struct sometype {
};

sometype foo() {
    sometype x         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 19:49

    What's wrong with sometype & a = foo(); ?

    foo() returns temporary so you cannot bind it to reference because it will no longer exists after the end of full expression (assignment line). The only way to extend its life time is to change it to const sometype & a = foo(); Or assign it to rvalue reference.

    Is sometype && b = foo(); actually rvalue reference?

    yes (read here for more: Do rvalue references allow dangling references?)

    Does it "steal" the return value from foo() and send what was in b to the destructor?

    no, it extends its lifetime

    Is there another way to not have this warning?

    You have three choices: (1) assign to rvalue reference, (2) assign to const lvalue reference, (3) return by value but implement move semantics in your class.

    You can also count on that compiler will perform RVO on returned value.

提交回复
热议问题