This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Copy constructor not called.


As far as I can tell:

Your assignment Operator does not return a reference, that's why the compiler complains about not finding a matching copy contructor. Afaik semantically ( b = a ) would yield a copy constructor to create a temporary for the RV, which is A and not A & in your case. I don't know though, why a const in the copy constructor fixes the compile error as well.


And I want to quote from the man page:
-fno-elide-constructors
The C++ standard allows an implementation to omit creating a tempo-
rary which is only used to initialize another object of the same
type. Specifying this option disables that optimization, and
forces G++ to call the copy constructor in all cases.



As I read this this only relates to temporarys used for initialization. I don't see any initialization, only a RV temporary passed to the assignment operator. Thus the RVO will still be done and not be disabled by that option, as I read it.


Regards

-Sven


Mustafa4LP schrieb:
Hi all,

Please consider the following program:

#include <iostream>
using namespace std;
class A
{
public:
   A ()
   {
      cout << "constructor" << endl;
   }
   A (A &a)
   {
      cout << "copy constructor" << endl;
   }
   A operator = (const A &a)
   {
      cout << "= operator" << endl;
   }
};
int main()
{
   A a;
   A b;
   b = ( b = a );
}


Following error is issued while running the above test case on gcc 3.4.6


test007.cpp: In function `int main()':
test007.cpp:23: error: no matching function for call to `A::A(A)'
test007.cpp:11: note: candidates are: A::A(A&)

However, if I change the argument of copy constructor to "const A &", the
program compiles finely.
I could not understand why const is required in copy constructor for running
the test case.

Also note that in the output of the modified program (which compiled
finely), no copy constructor is called.
I am running the test case with --no-elide-constructors option to disable
the RVO (so that I can get all copy constructor calls).

Thanks in advance for any help.

Regards,
Mustafa


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]