Pol
Pol

Reputation: 325

Returning rvalue references

I've seen other posts regarding this but I'm still quite a bit confused regarding this.

const std::string& func(std::string&& ref) { return ref; }

int main(void) {
  const std::string& r=func("E");
  std::cout << r << std::endl;
}

Now this should technically be UB, I'm returning a reference to "E" which should be destroyed after the expression that assigns to r is done, right? However, no warning from clang or g++, perhaps I am missing something?

const std::string& func(std::string ref) { return ref; }

int main(void) {
  const std::string& r=func("E");
  std::cout << r << std::endl;
}

Clang would warn about something like this. But, it doesn't warn about this:

const std::string& func(std::string ref) { return std::move(ref); }

int main(void) {  
  const std::string& r=func("E");
  std::cout << r << std::endl;  
}

It also doesn't warn about something like:

std::string&& func(std::string&& ref) { return std::move(ref); }

int main(void) {
  std::string&& r=func("E");
  std::cout << r << std::endl;  
}

Is this not UB after all?

If someone could clarify on these I'd be grateful.

Upvotes: 2

Views: 97

Answers (1)

eerorika
eerorika

Reputation: 238311

However, no warning from clang or g++, perhaps I am missing something?

Only thing that you're missing is the fact that compilers are not guaranteed nor required to warn about undefined behaviour and generally are not able to do so.

Is this not UB after all?

The behaviour of the program is undefined. Lack of a warning is not proof of well defined behaviour.


For what it's worth, both GCC and Clang detect this bug at runtime with AddressSanitizer.

Upvotes: 3

Related Questions