By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,851 Members | 2,097 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,851 IT Pros & Developers. It's quick & easy.

Contradictory behaviour of temporary objects

P: n/a
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 ?

Jun 10 '07 #1
Share this Question
Share on Google+
1 Reply


P: n/a
On 2007-06-10 12:15, sa**********@gmail.com wrote:
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 ?
No, this has nothing to do with what you can and can not do with
temporary objects, but rather what you can and can not do with
references. A temporary object is just like any other object. However
you can not bind a non-const reference to a temporary since there's a
possibility that you'd end up with stale references (ie. the reference
is still there when the temporary is not).

--
Erik Wikström
Jun 10 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.