| Title: | C++ |
| Notice: | Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS) |
| Moderator: | DECCXX::AMARTIN |
| Created: | Fri Nov 06 1987 |
| Last Modified: | Thu Jun 05 1997 |
| Last Successful Update: | Fri Jun 06 1997 |
| Number of topics: | 3604 |
| Total number of notes: | 18242 |
Is an expression of the form (x ? y : z) really equivalent to the 'if' form ?
Or do I get lost in the C++ land (simple overlook of some compiler generated
default member function) ? (See Worker::getIt() below)....
Versions: CXX T5.6-006 on Digital Unix 4.0B, CXX V5.5-017 on OpenVMS AXP 6.2.
Wolfgang
#include <iostream.h>
#include <string.hxx>
class vBase {
public:
static String stStr;
virtual const String & getStr() =0;
};
class derived : public vBase {
public:
virtual const String & getStr();
private:
String myString;
};
String vBase::stStr= "WWW";
const String &
derived::getStr() {
myString= "XXX";
return(myString);
}
class Worker {
public:
Worker();
~Worker();
const String & getIt();
private:
vBase *bP;
};
Worker::Worker() {
bP= new derived;
}
Worker::~Worker() {
delete bP;
}
const String &
Worker::getIt() {
/*
// produces the derised result
if (bP != 0)
return (bP -> getStr());
else
return (vBase::stStr);
*/
// doesn't work - prints nothing
return ( bP ?
bP -> getStr() : vBase::stStr);
}
int main ( void ) {
Worker x;
cout << x.getIt() << endl;
}
| T.R | Title | User | Personal Name | Date | Lines |
|---|---|---|---|---|---|
| 3587.1 | I'm not sure if it's a bug or feature... | DECC::J_WARD | Mon May 26 1997 17:18 | 20 | |
In the case of the ternary operator it looks like
the copy constructor is being called to copy the
return value of getStr() into a temporary and then that
local temporary is being returned by reference, i.e.
the code begin generated is equivalent to:
String tmp = bP->getStr();
return bP ? tmp : vBase::stStr;
I can see why the above code would give you random
problems, since you are returning a local variable
by reference and it may be destroyed before it
is used.
In the if-else case no copy constructor is ever
called for String.
Perhaps someone else can comment on whether
this is a compiler bug or user bug?
| |||||
| 3587.2 | Also not sure | MUNICH::WWERNER | When in doubt, do as the INTs do | Tue May 27 1997 04:47 | 4 |
The question is: is it correct that the copy constructor is called ? The program deals with references not objects... Wolfgang | |||||
| 3587.3 | Noted | DECCXX::AMARTIN | Alan H. Martin | Tue May 27 1997 16:28 | 6 |
Re .2: >The question is: is it correct that the copy constructor is called ? I don't know. I've logged a bug report. /AHM | |||||