This is the mail archive of the gcc-bugs@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]

Strange use of Copy Constructor of gcc version 2.95.1 19990816 (release)


System: Linux kernal 2.2.x
Compiler:  gcc version 2.95.1 19990816 (release)

I detected a strange behavior in use of copy constructors:

in the following short program ...

----------------example 1--------------------
#include <assert.h>
#include <iostream>


class P {
    int* mP;
public:
    P():mP(0) {}

    P(const P& p):mP(0) { std::cout<<"copy const"<<endl; assert(p.mP==0); }

    P(P& p):mP(p.mP) { p.mP=0; std::cout<<this<<" copy "<<&p<<endl; }

    P(int* pi):mP(pi) {}

    ~P() { std::cout<<"destr: "<<this<<" = "<<mP<<endl; }

    P& operator=(P p) { mP = p.mP; p.mP = 0; return *this; }
};

int i;

P generate_a_special_pointer()
{
    P p=&i;
    /* do something ... */
    return p;
}

int main()
{
    P p1 = generate_a_special_pointer();
}
-------------------end of example 1---------------------

... the compilition works well and running the programm yields in the
output:

schuette > a.out
0xbffff6e8 copy 0xbffff6a8
destr: 0xbffff6a8 = (nil)
destr: 0xbffff6e8 = 0x8049c38

So it seems that the tempo generated by the function
generate_a_special_pointer() is copied into
object p1 via the CopyConstr  P(P& p).

Now I would prefer not to have the CopyConstr P(const P& p) at all.
Commenting out its declaration/definition yields in a Error message
of the compiler:

--------------------example 2---------------------
#include <assert.h>
#include <iostream>


class P {
    int* mP;
public:
    P():mP(0) {}

//    P(const P& p):mP(0) { std::cout<<"copy const"<<endl; assert(p.mP==0); }

    P(P& p):mP(p.mP) { p.mP=0; std::cout<<this<<" copy "<<&p<<endl; }

    P(int* pi):mP(pi) {}

    ~P() { std::cout<<"destr: "<<this<<" = "<<mP<<endl; }

    P& operator=(P p) { mP = p.mP; p.mP = 0; return *this; }
};

int i;

P generate_a_special_pointer()
{
    P p=&i;
    /* do something ... */
    return p;
}

int main()
{
    P p1 = generate_a_special_pointer();
}
-----------------end of example 2 ---------------

schuette c/ilist> g++ bug.C
bug.C: In function `class P generate_a_special_pointer()':
bug.C:25: initialization of non-const reference type `class P &'
bug.C:25: from rvalue of type `P'
bug.C:12: in passing argument 1 of `P::P(P &)'
bug.C: In function `int main()':
bug.C:32: initialization of non-const reference type `class P &'
bug.C:32: from rvalue of type `P'
bug.C:12: in passing argument 1 of `P::P(P &)'


So, since P(const P&) is not declared any more, it seems that the
compiler does not allow now, what has happened without any warnings in
the previous example.

This seems to be strange ...

Best greetings

Thomas


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