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

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

Date: Tue, 30 Apr 2013 09:44:01 +0000

To: Vladimir Marek

Cc: Tomi Ollila, notmuch@notmuchmail.org

From: Kim Minh Kaplan


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.

Thread: