Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are unnamed objects and temporary objects equivalent?

Tags:

c++

In my effort to understand rvalue references, I have been pondering when the compiler will determine that a particular function argument is an rvalue reference, and when it will determine it to be an lvalue reference.

(This issue is related to reference collapsing; see Concise explanation of reference collapsing rules requested: (1) A& & -> A& , (2) A& && -> A& , (3) A&& & -> A& , and (4) A&& && -> A&&).

In particular, I have been considering if the compiler will always treat unnamed objects as rvalue references and/or if the compiler will always treat temporary objects as rvalue references.

In turn, this leads me to question whether unnamed objects are equivalent to temporary objects.

My question is: Are unnamed objects always temporary; and are temporary objects always unnamed?

In other words: Are unnamed objects and temporary objects equivalent?

like image 499
Dan Nissenbaum Avatar asked Dec 05 '12 18:12

Dan Nissenbaum


2 Answers

I might be wrong, since I'm not sure what the definition of "unnamed object" is. But consider the argument of the foo() function below:

void foo(int)
{ /* ... */ }

int main()
{ foo(5); }

foo()'s argument is unnamed, but it's not a temporary. Therefore, unnamed objects and temporary objects are not equivalent.

like image 64
Nikos C. Avatar answered Nov 15 '22 09:11

Nikos C.


Temporary objects can be named.

Very common case - when passed as a parameter to a function. Another less common case - binding a const reference to an rvalue result of a function.

int f(int i) { return i + 1; }
int g() { const int &j = f(1); return j; }

Unnamed objects are often temporary, but not always. For example - anonymous union object:

struct S
{
   union { int x; char y; };
} s;

And, of course, any object created by operator new.

Perhaps there are other cases, but even only these can serve as counterexamples to the hypothesis :)

like image 29
chill Avatar answered Nov 15 '22 10:11

chill