[Search for users] [Overall Top Noters] [List of all Conferences] [Download this site]

Conference turris::c_plus_plus

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

3587.0. "question about the ternary operator '?'" by MUNICH::WWERNER (When in doubt, do as the INTs do) Mon May 26 1997 09:47

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.RTitleUserPersonal
Name
DateLines
3587.1I'm not sure if it's a bug or feature...DECC::J_WARDMon May 26 1997 18:1820
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.2Also not sureMUNICH::WWERNERWhen in doubt, do as the INTs doTue May 27 1997 05:474
The question is: is it correct that the copy constructor is called ?
The program deals with references not objects... 

Wolfgang
3587.3NotedDECCXX::AMARTINAlan H. MartinTue May 27 1997 17:286
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