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]

Is this the standard behavior ?


I have a strange problem while porting a program from SUNWspro 4 C++
compiler to GNU g++ 2.92.2

I heared that in old C++ standard a copy constructor could be C::C(C&),
but in modern C++ it should be C::C(const C &).

In the program that I work with the old variant is used.
So on compilation g++ gives error messages like the following:

  qs.cpp:26: initialization of non-const reference type `class C &'
  qs.cpp:26: from rvalue of type `C'
  qs.h:14: in passing argument 1 of `C::C(C &)'

Ok, I understand what is happening. No problem.

But one class in the program defines also operator char *() and
constructor C::C(char*):

class C {
  public:
    ...
    C ( C & );
    C ( char * );
    operator char * ();
    ~C();
    ...
  }

Now let e.g. have

C f ( void )  { return "xxx"; }

In this case, g++ does a really strange thing.
No errors or warnings (even with -W -Wall) are issued.
In the assembler code I see the following. First constructor C::C(char
*) is called to create an object in function f's local stack frame.
Then, the operator char * is called for this object. Then, another C
object is created (in the stack frame of the caller function). Then,
destructor C::~C() is called to destroy the first C object.

This causes bad errors. Pointer returned from operator char * of the
first object is stored in the second object, but becomes invalid after
the first object is deleted. So there is an invalid usage of heap memory
and the program crashes soon.

I agree that it is a bad design to store a pointer to an external object
in the class constructor, but to delete this external object in the
destructor. But the fact is that the program uses it, program is huge so
redesign of data structure is a very hard task, the program works
correctly when compiled by Sun CC (it just issues some warnings about
C::C(C&) is obsolete), but it doesn't work with g++ 2.95.2. And my task
is to port it in hard time limits :-(((.

My question are:
  is the behaviour of g++ correct ?
  is this behaviour required by the modern C++ standard ?
  is it good to call implicitly the pair (operator char *,
     C(char *)) without even issuing a warning ?  Is this
     standard ?
  are there any g++ command-line swithes or other parameters
     that will make it to behave like Sun CC (that is, just
     to call constructor of the returned object)
  maybe, there are some workarounds ?

Great thanks for any help.
If possible, please reply by e-mail to yoush@cs.msu.su

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