help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Copy constructor, or assingment operator not being called.


From: manu
Subject: Copy constructor, or assingment operator not being called.
Date: 21 Oct 2004 08:26:08 -0700

I have a strange problem with a program.
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!

It should make an a object, and then a copy to pass it as return
value, but it doesn't.

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?
I'm working with GCC version 3.3.4 (Debian).


Thank you.


reply via email to

[Prev in Thread] Current Thread [Next in Thread]