Y
yevvio
Hi, sorry, messed up my previous post...
Consider the following code:
class A {
int x;
public:
A() { printf("In A()\n"); x = 5; }
~A() { printf("In ~A()\n"); }
operator int *() { printf("In int *()\n"); return &x; }
};
A f1()
{
printf("in f1()\n");
return A();
}
void foo(int *p) { printf("in foo()\n"); }
int main()
{
foo(f1());
printf("After foo()\n");
return 0;
}
I have always thought this code is wrong because the temporary object
A would be destroyed after calling int *() operator and before
entering foo(), so the pointer p would point to freed memory. However
i complied the code in both vs2005 and gcc compilers and ran it, it
complies fine and the result in both cases is the following:
in f1()
In A()
In int *()
in foo()
In ~A()
After foo()
That means that temporary A is kept alive for the duration of function
foo().
So what should be correct behaviour according to c++ standard
regarding when the temporary is freed? Is the code above portable?
Thanks
Yev
Consider the following code:
class A {
int x;
public:
A() { printf("In A()\n"); x = 5; }
~A() { printf("In ~A()\n"); }
operator int *() { printf("In int *()\n"); return &x; }
};
A f1()
{
printf("in f1()\n");
return A();
}
void foo(int *p) { printf("in foo()\n"); }
int main()
{
foo(f1());
printf("After foo()\n");
return 0;
}
I have always thought this code is wrong because the temporary object
A would be destroyed after calling int *() operator and before
entering foo(), so the pointer p would point to freed memory. However
i complied the code in both vs2005 and gcc compilers and ran it, it
complies fine and the result in both cases is the following:
in f1()
In A()
In int *()
in foo()
In ~A()
After foo()
That means that temporary A is kept alive for the duration of function
foo().
So what should be correct behaviour according to c++ standard
regarding when the temporary is freed? Is the code above portable?
Thanks
Yev