Image

Imageataxi wrote in Imagecpp

pass by value - any construction guarantees?

Consider this code:
#include 

using namespace std;

struct aclass
{
  aclass() { cout << "default ctor" << endl; }
  aclass(const aclass& a) { cout << "copy ctor" << endl;}
  ~aclass() {cout << "dtor" << endl;}
};

void foo(aclass a)
{
  cout << "foo" << endl;
}

int main(int, char*[])
{
  foo(aclass());
  return 0;
}
Under Visual Studio 7.1 this generates the output
#1
default ctor
foo
dtor
If you change the main line to aclass a; foo(a); then the output becomes
#1
default ctor
copy ctor
foo
dtor
dtor
i.e. the copy constructor (which has an observable side effect) does get called, where previously it wasn't. Anyone know what the C++ standard says about specifying a temporary object as a pass by value argument to a function?

It worries me that a copy constructor that I thought would be called (and that has a side effect) was either optimised away incorrectly, or never guaranteed to be called in the first place.

Also, if no custom copy constructor is specified, the default, compiler-supplied bitwise copy constructor of aclass does appear to get called, or at least the destructor gets invoked twice as above in the second instance (same output as #2 above without the "copy ctor" line). I'm finding it bizarre that a copy is created only in the instance where copying doesn't actually have a side effect.