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

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

Date: Wed, 1 May 2013 13:28:06 +0200

To: Kim Minh Kaplan

Cc: Tomi Ollila, notmuch@notmuchmail.org, Vladimir Marek

From: Vladimir Marek


> 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

Thread: