public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Temporary objects
@ 2007-06-11  9:13 Aseem Rastogi
  2007-06-18 16:25 ` John Love-Jensen
  0 siblings, 1 reply; 2+ messages in thread
From: Aseem Rastogi @ 2007-06-11  9:13 UTC (permalink / raw)
  To: gcc-help

Hi All,

I find following C++ behaviour regarding temporary objects quite
contradictory. Consider this:

class A
{
    ...

    public:
        void bar () { ... } // non-const member function

};

A getA () { ... } // return an object

void foo (A& a) { ... }

int main ()
{
    foo (getA ()); // error: not allowed to pass temporary object as
non-const reference. acceptable.

    getA ().bar (); // why is this allowed ?? calling a non-const
functrion on a temporary object ?

}

Any ideas why it could be so ?

If passing a temporary object as non-const reference is not allowed
because making changes to it doesn't make sense, doesn't same thing
apply to calling non-const member function on a temporary ?

Thanks in advance,

-Aseem.

^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: Temporary objects
  2007-06-11  9:13 Temporary objects Aseem Rastogi
@ 2007-06-18 16:25 ` John Love-Jensen
  0 siblings, 0 replies; 2+ messages in thread
From: John Love-Jensen @ 2007-06-18 16:25 UTC (permalink / raw)
  To: Aseem Rastogi, MSX to GCC

Hi Aseem,

> Any ideas why [passing temporary objects as non-const reference] could be [an
error] ?

C++ can generate unexpected temporaries, which when passed into functions
that are declared to mutate the temporary that can result in extremely
difficult to diagnose bugs.

As such, temporaries are not allowed to be passed to in/out and out
parameters.

> If passing a temporary object as non-const reference is not allowed
> because making changes to it doesn't make sense, doesn't same thing
> apply to calling non-const member function on a temporary ?

No.  It's not a const related issue.  It's an issue related to temporaries,
and C++'s rather promiscuous conversions.

If C++ required explicit conversions, it wouldn't be a problem.  But then
the code wouldn't be C++ as we have it today.  And we'd have a different set
of problems (such as problems regarding code verbosity, legibility,
maintainability).

> Thanks in advance,

You're welcome.

Sincerely,
--Eljay

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2007-06-18 14:28 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2007-06-11  9:13 Temporary objects Aseem Rastogi
2007-06-18 16:25 ` John Love-Jensen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).