[PATCH] don't store temporary value returned from c_str()
Vladimir Marek
Vladimir.Marek at Oracle.COM
Tue Apr 30 01:48:52 PDT 2013
Hi,
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".
I still believe my fix is correct, but I'm not at the position to be
able to defend it at the moment :)
Thank you
--
Vlad
> The january 2012 working draft:
> http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
>
> 12.2 Temporary objects [class.temporary]
>
> 1 Temporaries of class type are created in various contexts: binding a
> reference to a prvalue (8.5.3), returning a prvalue (6.6.3) […]
>
> 3 When an implementation introduces a temporary object of a class that
> has a non-trivial constructor (12.1, 12.8), it shall ensure that a
> constructor is called for the temporary object. Similarly, the
> destructor shall be called for a temporary with a non-trivial destructor
> (12.4). Temporary objects are destroyed as the last step in evaluating
> the full-expression (1.9) that (lexically) contains the point where they
> were created.
-------------- next part --------------
#include <stdio.h>
#include <vector>
#include <string.h>
using namespace std;
class array {
vector<char> impl;
public:
array(int size):impl(size) { }
array(array &in):impl(in.impl) { }
char*
operator[](size_t i) {
return &impl[i];
};
~array() {
strcpy(&impl[0], "destroyed");
}
};
class str {
array tmp;
public:
str(const char *input):tmp(100) {
strcpy(tmp[0], input);
};
const char* c_str() {
return (array(tmp))[0];
};
};
int
main (int argc, char **argv)
{
str s("test");
const char *x;
printf ("%s\n", s.c_str());
x=s.c_str();
printf ("%s\n", x);
return 0;
}
More information about the notmuch
mailing list