0

The following code exhibits undefined behaviour:

#include <memory>

void consumer(std::string && str){}

int main(){

  std::string str = "foo";
  consumer(std::move(str));
  str = "bar"; //<- UB
}

How can I catch this? There doesn't appear to be any compiler warnings in gcc or clang.

I also tried using the undefined behaviour sanitizer:

clang++-3.9 -std=c++1z -g -Weverything -fsanitize=undefined  -o main main.cpp  

It did not catch anything.
Are there reliable ways to catch these problems?

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 2
    Why UB? Re-assigning a moved-from object a new value is a well-defined behavior. – Sergey Kalinichenko Jun 30 '16 at 04:45
  • What makes you believe this code exhibits undefined behavior? Looks fine to me. – Igor Tandetnik Jun 30 '16 at 04:45
  • I see. I misunderstood, and thought it was UB. – Trevor Hickey Jun 30 '16 at 04:46
  • 3
    Note that you don't even have a moved from object here. Your function doesn't consume anything at all. The "valid but unspecified state" does not apply. The state of `str` is both valid and well-specified.`str == "foo"` before and after the call to `consumer`. – Benjamin Lindley Jun 30 '16 at 04:59
  • @BenjaminLindley Why doesn't the function consume? Because its not using the parameter in the body? – Trevor Hickey Jun 30 '16 at 05:04
  • @TrevorHickey: Well, it depends upon what you mean by consume. I assumed you meant that the object was moved. It wasn't. Moving happens when the move constructor or move assignment operator is called. You didn't do that anywhere, you just passed the object by reference to a function, and didn't modify it in any way. – Benjamin Lindley Jun 30 '16 at 05:06
  • @BenjaminLindley I got the "consume" terminology from the C++ guidelines: http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#a-namerf-consumeaf18-for-consume-parameters-pass-by-x-and-stdmove-the-parameter – Trevor Hickey Jun 30 '16 at 05:08

0 Answers0