Topic: Avoiding Problems Due to Early Destruction of Temporaries


Author: john@bnrmtl.bnr.ca (John Hickin)
Date: 8 Nov 91 14:26:21 GMT
Raw View
I have tried, without success, to get around some of the problems associated
with the early destruction of compiler generated temporaries (for examples
see the ARM in chapter 12).  Can anybody tell me if the following should work?

    class String {
       char* PData;
    public:
       String();
       String( const char* );
       String( const String& );
       //etc.

       operator const char*()  { return PData; }
       // Non-const member function by design.
    };

String :: operator const char*() is the source of the problem.  By making it
non-const (even though the compiler can TELL that it is (Alice) const) I hoped
to bar the compiler from applying it to generated temporary String's.

I tried two compilers out on the following client code:

    String foo() { return "foo"; }

    main() {
 const String bar( "bar" );
 cerr << foo() << endl;  // warning expected but not seen
 cerr << bar   << endl; // warning here
    }

and each warned about the use of the cast on the const bar but neither
issued a warning about its application to the value returned by foo().
I had thought that such function returns were copied into const temporaries
and should therefore have been warned.

Can anybody help me out?

--
John Hickin      Bell-Northern Research, Montreal, Quebec
(514) 765-8888   bnrmtl!john@larry.mcrcim.mcgill.edu