shaanxxx wrote:
ge***********@gmail.com wrote:
I've been trying to pin down the scoping rules for temporary variables
in C++. I know that doing something like:
string s("abc");
const char *t = (s+"def").c_str();
cout << t;
is invalid since (s+"def") creates a temporary which goes out of scope,
thus leaving t a dangling pointer. What I'm wondering is whether
temporaries go out of scope when their expression terminates or when
their statement terminates. For example, is the following wrong?
string s("abc");
cout << (s+"def").c_str();
scope of temporaries would be the block in which temporaries are
defined.
I'm pretty sure the scoping of temporaries is tighter than block level.
The following code:
class dstring : public string
{
public:
dstring(const char *s) : string(s), i(n++) {};
dstring(string const &s) : string(s), i(n++) {};
virtual ~dstring() { cout << "dstring " << i << " destructing\n";
}
dstring operator+(const char *s) { return dstring((string)*this +
s); }
private:
int i;
static int n;
};
int dstring::n = 0;
void dstringTests()
{
const char *t = (dstring("abc") + "def").c_str();
printf("t = '%s'\n\n", t);
printf("inlined = '%s'\n", (dstring("abc") + "def").c_str());
printf("\n");
printf("inlined#2 = '%s'\n", (dstring("abc") + "def").c_str());
printf("\n");
}
outputs:
dstring 1 destructing
dstring 0 destructing
t = ''
inlined = 'abcdef'
dstring 3 destructing
dstring 2 destructing
inlined#2 = 'abcdef'
dstring 5 destructing
dstring 4 destructing
If the scoping of temporaries was block-level, none of the "dstring x
destructing" lines would be printed until after the "x = y" lines.
These results are for VS2005, g++ 3.3.5, and g++ 3.4.4, with and
without optimizations.