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

Kim Minh Kaplan kimminh.kaplan+nomuch at afnic.fr
Tue Apr 30 02:44:01 PDT 2013


Vladimir Marek :

> Thank you, I found it eventually too. But I wrote little test program
> (attached) which confused me. I haven't had much time to take a look
> into it since weekend.
>
> The idea is to have temporary object where I can detect whether
> destructor was called.
>
> I thought that
>
> printf ("%s\n", s.c_str());
> will print "test"
>
> and
>
> x=s.c_str();
> printf ("%s\n", x);
>
> will print "destroyed"
>
> On my machine both prints "destroyed".

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);
    }

Kim Minh.


More information about the notmuch mailing list