*
pe*******@hotmail.com:
Hi, try the following code with flag=0/1/2.
Better use meaningful names than magic numbers like 0, 1 and 2.
#include<iostream>
using namespace std;
#define flag 2//option:0,1,2
class C
{
public:
C(){cout<<"C"<<endl;}
#if flag==1
C(C&){cout<<"C"<<endl;}
#endif
virtual ~C(){cout<<"~C"<<endl;}
};
Why is the diagnostic output for copy construction limited to flag=1?
#if flag==0
void myfunc(C)
{
}
#elif flag==1
void myfunc(C)
{
}
#elif flag==2
void myfunc(C&)
{
}
#endif
int _tmain(int argc, _TCHAR* argv[])
This is not standard C++. It should not compile. In standard C++ you have
int main()
See, it's even less to write! ;-)
{
cout<<"flag="<<flag<<endl;
C myC;
myfunc(myC);
return 0;
}
/*
result:
flag=0
C
~C
~C
flag=1
C
C
~C
~C
flag=2
C
~C
*/
It really surprized me that when flag=0, I got C called [only] once
Depends what you mean by "C". There are two constructor calls but only
one default constructor call.
with ~C
called twice.
The destructor is also, with your compiler etc., called twice for
flag=1, according to the output above.
It's no mystery.
'myfunc' takes a C argument by value, which means a copy is (logically)
made, which means a separate C object whose destructor must be called.
I know that if more ctor are called than dtor, then there
is a memory leak.
No, that's an unwarranted conclusion, and anyway it's not what's
happening here. However, /if/ this happens then you're off in Undefined
Behavior land, so anything might happen. Depends on compiler etc..
But what happened when more dtor is called than ctor?
You mean above?
What happended was that your code displayed "~C" twice and "C" only once.
Then you drew untenable conclusions from your program's less than
complete diagnostic output.
Does anybody know relevant specification in C++ standard?
Yes. If you don't do fancy things with very low-level features, you'll
get exactly as many destructor calls as /successful/ constructor calls.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?