[PATCH] don't store temporary value returned from c_str()

Vladimir Marek Vladimir.Marek at Oracle.COM
Wed May 1 04:28:06 PDT 2013


> You have to somehow instantiate a temporary object, using a function
> call for example.
> 
>     #include <string.h>
>     #include <stdio.h>
>     struct example {
>       char data[10];
>       char *c_str() { return data; }
>      example() { strcpy(data, "test"); }
>       ~example() { strcpy(data, "destroyed"); }
>     };
>     example foo()
>     {
>       example res;
>       return res;
>     }
>     main()
>     {
>       printf("%s\n", foo().c_str());
>       char *x = foo().c_str();
>       printf("%s\n", x);
>     }

Right. After more tests I think I'm getting hang of it. In my examples I
had function similar to

char *foo() {
  example res;
  return res.c_str();
}

In this case the reference returned is to _char pointer_ and not to
example struct. So the struct is destroyed before returning from foo to
caller. Compiler does not understand that the returned char pointer does
not have any meaning without the example struct.

This is where I was doing the mistake, I believe.

Thank you
-- 
	Vlad


More information about the notmuch mailing list