Temporary Objects as reference argument in functions

Long Li long21st@yahoo.com
Sun Jun 8 06:57:00 GMT 2003


In C++, temporary objects are treated as const, so one
way to solve the problem is to change 

void test(MyClass & rTest)
{
}

to

void test(const MyClass &rTest)
{
}


Best,



Long

--- Dirk Volkmar <Dirk.Volkmar@deutsche-boerse.com>
wrote:
> Hi!
> 
> We are porting some software to linux, that runs
> under solaris and windows.  On
> these plattforms we use the native compilers
> (workshop/devstudio).
> We have a problem with temporary objects that are
> passes to functions with
> reference parameters. I stripped the code down to an
> example that looks like the
> following code:
> 
> class MyClass
> {
>      public:
>           MyClass(long lLong) : m_lLong(lLong) {};
>      protected:
>           long m_lLong;
> };
> 
> void test(MyClass & rTest)
> {
> }
> void test(const char * szTest)
> {
> }
> int main()
> {
>      test(MyClass(1));
>      return 0;
> }
> 
> The compiler gives the following output:
> g++ -c main.cpp
> main.cpp: In function `int main()':
> main.cpp:17: error: no matching function for call to
> `test(MyClass)'
> main.cpp:10: error: candidates are: void
> test(MyClass&)
> main.cpp:13: error:                 void test(const
> char*)
> 
> If I delete the second test function I get the
> following
> g++ -c main.cpp
> main.cpp: In function `int main()':
> main.cpp:17: error: could not convert `MyClass(1)'
> to `MyClass&'
> main.cpp:10: error: in passing argument 1 of `void
> test(MyClass&)'
> 
> If I declare a local object  instead using a
> temporary object, it works:
> int main()
> {
>      MyClass aObject(1);
>      test(aObject);
>      return 0;
> }
> 
> Looking into the ansi standard I couldn't find that
> the code is illeagal. Sun
> Workshop and Dev Studio have no problems with it,
> why not gcc?
> O.K. I can use the upper workaround, but it is
> anoying to change hundreds of
> lines and don't know  why.
> If someone has an explanation for this I would be
> very happy.
> 
> Bye Dirk
> 
> --
> Diese E-Mail enthaelt vertrauliche oder rechtlich
> geschuetzte Informationen.
> Wenn Sie nicht der beabsichtigte Empfaenger sind,
> informieren Sie bitte
> sofort den Absender und loeschen Sie diese E-Mail.
> Das unbefugte Kopieren
> dieser E-Mail oder die unbefugte Weitergabe der
> enthaltenenen Informationen
> ist nicht gestattet.
> 
> The information contained in this message is
> confidential or protected by
> law. If you are not the intended recipient, please
> contact the sender and
> delete this message. Any unauthorised copying of
> this message or
> unauthorised distribution of the information
> contained herein is prohibited.
> 
> 


__________________________________
Do you Yahoo!?
Yahoo! Calendar - Free online calendar with sync to Outlook(TM).
http://calendar.yahoo.com



More information about the Gcc-help mailing list