Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an anonymous variable by reference

Standard C++ types such as int or char have ctors, so you can have expressions like:

int a = int(67); // create anonymous variable and assing it to variable a
int b(13);       // initialize variable b
int(77);         // create anonymous variable

User defined types (structures or classes) are able to do the same:

struct STRUCT
{
  STRUCT(int a){}
};

STRUCT c = STRUCT(67);
STRUCT d(13);
STRUCT(77);

The question is: why can we pass by a reference anonymous structure or class instances, but can not pass standard types?

struct STRUCT
{
  STRUCT(int a){}
};

void func1(int& i){}
void func2(STRUCT& s){}
void func3(int i){}
void func4(STRUCT s){}

void main()
{
  //func1(int(56));  // ERROR: C2664
  func2(STRUCT(65)); // OK: anonymous object is created then assigned to a reference
  func3(int(46));    // OK: anonymous int is created then assigned to a parameter
  func4(STRUCT(12)); // OK: anonymous object is created then assigned to a parameter
}
like image 565
Ivars Avatar asked Nov 09 '13 12:11

Ivars


1 Answers

If your compiler allows this, then it's not a standard compatible C++ compiler. You can not bind a temporary rvalue to a non-const lvalue reference. It's the rule. Both clang and gcc don't compile that code for func2(STRUCT(65));.

Instead you have alternatives:

void func1(int&& i){}

void func1(const int& i){}

Legacy from C++03: A (lvalue) reference to a non-const type (int &i) supposed to able to change the parameter then passing a temporary object such as 56 is not logical because it not changeable. A reference to a const type (const int &i) supposed to just observe the value as read-only, then passing a temporary value such as 52 is legal.

In C++11 you can reference to a non-const temporary object by &&.

like image 116
masoud Avatar answered Sep 20 '22 04:09

masoud