Stupid Function | Academic purposes

Jul 7, 2011 at 5:28pm
I was going through constructors and while I was checking the copy constructor, my mind was set away.

I defined a class Scale and I was seeing how many times the copy constructor got called.

1
2
3
4
Scale nothing(const Scale &a)
{
    return a;
}


During this function it gets called once. I assume it is during the return statement. Meaning that it returns a copy of a and not a itself.

Can anyone confirm this?

Also what if for no reason at all I want it to return a itself and not a copy? (I know it makes no sense but curiosity is kicking in, strongly)

When I tryed:

1
2
3
4
Scale& nothing(const Scale &a)
{
    return &a;
}


C::B got angry at me and spitted this out:

1
2
3
o\Cpp\scales\main.cpp||In function 'Scale& nothing(const Scale&)':|
o\Cpp\scales\main.cpp|9|error: invalid initialization of non-const reference of type 'Scale&' from a temporary of type 'const Scale*'|
||=== Build finished: 1 errors, 0 warnings ===|

Jul 7, 2011 at 7:30pm
I assume it is during the return statement.
That's right.

The problem of your function is that constness is lost. Make it return a const reference and it will work. If your function worked, const keyword would loose any purpose.

By the way, if you care about when copy constructor is called, you may want to know about http://en.wikipedia.org/wiki/Return_value_optimization
Jul 7, 2011 at 9:32pm
Indeed worked.

RVO was what I was trying to see if could work. Apparently it can. :)

Thank's,

Hugo Ribeira
Jul 8, 2011 at 3:16am

I put;

1
2
3
4
5
6
7
8
// for constructors
   cout << "ctr_<object name here>:" << this << endl;

//for destructors
      cout << "dtr_<object name here>:" << this << endl;

//for copy constructors
      cout << "cctr_<object name here>:" << this << endl;


so that I can see which object sits where in memory. and I know when ctr/dtr/cctr calls are made.
it helps me a lot.. I can clearly see what's going on.

recommend you to do the same.
Jul 8, 2011 at 4:20pm
I do the the same, but thanks anyway. ;)
Topic archived. No new replies allowed.