문제

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
}
도움이 되었습니까?

해결책

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 &&.

다른 팁

It seems that you are using MS VC++ compiler that has such bug.:) You have to bind temporary object with const reference. For example you may write

const int &ri = 10;

but you may not write

int &ri = 10;

The same is valid for user-defined types.

const STRUCT &rs = STRUCT( 10 );

STRUCT &rs = STRUCT( 10 ); // the compiler shall issue an error.

In c++,an anonymous temporary object is always a right-value.To accept an right-value as argument,you can:

1).void foo1(TYPE); //passing by value
2).void foo2(const TYPE &); //passing by const reference
3).void foo3(TYPE &&); //in c++11,passing by right-value reference

Your "func3" and "func4" accept an argument that passed by value,it's ok.
However,"func1" and "func2" can only accept an argument that passed by a left-value reference.So it's wrong to pass an anonymous parameter.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top