Visual Studio C++ .NET 2003 Compiler optimization (Bug ?)

  • Thread starter Thread starter Piggy
  • Start date Start date
P

Piggy

using namespace std;
class foobar {
public:
foobar() { cout << "foobar::foobar()\n"; }
~foobar() { cout << "foobar::~foobar()\n"; }
foobar(int nval ):_ival(nval) { cout << "foobar::foobar(int)\n"; }
foobar( const foobar &rhs ) { cout << "foobar::foobar( const foobar
& )\n"; }
operator int(){ cout<<"foobar::operator int()"<<endl; return _ival; }
private:
int _ival;
};


foobar f( int val )
{
return foobar();
}

void main()
{
foobar foo = f(1024);
}


In the above program,

I see 3 different behaviors:
1. Run the program as it is, only one foobar object is created.
2. Remove the const qualifier from the copy constructor, there are 3 foobar
objects created. Strange thing is that "operator int()" method is used while
copying data to temporary objects. Why?
3. commenting the "operator int()" method will result back in only one
foobar object creation.

Could anyone kindly explain the behavior for me?
 
using namespace std;
class foobar {
public:
foobar() { cout << "foobar::foobar()\n"; }
~foobar() { cout << "foobar::~foobar()\n"; }
foobar(int nval ):_ival(nval) { cout << "foobar::foobar(int)\n"; }
foobar( const foobar &rhs ) { cout << "foobar::foobar( const foobar
& )\n"; }
operator int(){ cout<<"foobar::operator int()"<<endl; return _ival; }
private:
int _ival;
};


foobar f( int val )
{
return foobar();
}

void main()
{
foobar foo = f(1024);
}


In the above program,

I see 3 different behaviors:
1. Run the program as it is, only one foobar object is created.

2. Remove the const qualifier from the copy constructor, there are 3 foobar
objects created. Strange thing is that "operator int()" method is used while
copying data to temporary objects. Why?
3. commenting the "operator int()" method will result back in only one
foobar object creation.

Could anyone kindly explain the behavior for me?

I'm feeling a strong sense of déjà vu here, and no wonder! You posted the
same message back on Jan 9 in microsoft.public.vc.language and got several
good replies there on that same day:

http://groups.google.com/group/micr...17909524213/bdcb0b8834b550c6#bdcb0b8834b550c6
 
Back
Top