[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Copy constructor, or assingment operator not being called.
From: |
Guy Harrison |
Subject: |
Re: Copy constructor, or assingment operator not being called. |
Date: |
Thu, 21 Oct 2004 19:00:07 GMT |
User-agent: |
KNode/0.7.7 |
manu wrote:
> I have a strange problem with a program.
-ansi -pedantic -W -Wall -Werror
Hint: "return *this"
> I've reduced the code to the following working program.
>
> ----- Code -----
>
> class a
> {
> public:
> a () : _i (0)
> {
> ++_s_count;
> std::cout << "Creating a." << std::endl;
> }
> a (int i)
> : _i (i)
> {
> ++_s_count;
> std::cout << "Creating a with " << i << " value." <<
> std::endl;
> }
> a (const a & p) : _i (p._i)
> {
> ++_s_count;
> std::cout << "Copying a, value " << p._i << "." <<
> std::endl;
> }
> ~a ()
> {
> --_s_count;
> std::cout << "Destroying a." << std::endl;
> }
> a & operator= (const a & p)
> {
> std::cout << "Assigning a, value " << p._i << "." <<
> std::endl;
> }
> int print () { return _i; }
> void dump () { std::cout << "_s_count=" << _s_count <<
> std::endl; }
> private:
> static int _s_count;
> int _i;
> };
>
> int a::_s_count = 0;
>
> a makeA ()
> {
> a z(1);
> return z;
> }
>
> int main (void)
> {
> a na = makeA();
>
> std::cout << "Value: " << na.print() << std::endl;
>
> na.dump ();
>
> return 0;
> }
>
> ----- End code -----
>
> The problem is that in the makeA function, no copy constructor is
> being called. And I don't know why!
'z' has an int ctor so is constructed directly.
//hint: a z(1),x(z);
> It should make an a object, and then a copy to pass it as return
> value, but it doesn't.
Strictly, yes. Compiler optimisation. No point making an exact duplicate of
something that can be passed back directly.
> Output is:
>
> Creating a with 1 value.
> Value: 1
> _s_count=1
> Destroying a.
>
> It should be at least 2 objects, may be even 3. (In function 1,
> parameter 2 and assignment in main 3)
>
> Am I wrong? Am I missing something?
Nope. If an object never got created then it's a safe bet that "not
destroying it" will work. Provided 'na' ends up with contents of 'z' then
job done. For a correctly written object, even if it does invoke all the
theoretical steps it'll still work.
> I'm working with GCC version 3.3.4 (Debian).
Handy development tip...
For any class, plonk its cctor and ator in the private section. That'll
cause the compiler to moan if *any* other code tries to copy construct or
assign off that object (if you want it you can implement it but finding an
unwanted default one is pita).