通过引用传递匿名变量 [英] Passing an anonymous variable by reference

查看:72
本文介绍了通过引用传递匿名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准的 C++ 类型,如 int 或 char 有构造函数,所以你可以有这样的表达式:

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
}

推荐答案

如果您的编译器允许这样做,那么它就不是标准兼容的 C++ 编译器.您不能将临时右值绑定到非常量左值引用.这是规矩.clanggcc 不要为 func2(STRUCT(65)); 编译该代码.

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));.

相反,您有其他选择:

void func1(int&& i){}

void func1(const int& i){}

C++03 遗留问题:对非常量类型 (int &i) 的(左值)引用应该能够更改参数,然后传递一个临时对象,例如 56 不合逻辑,因为它不可更改.对 const 类型 (const int &i) 的引用应该只是将值观察为只读,然后传递诸如 52 之类的临时值是合法的.

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.

在 C++11 中,您可以通过 && 引用非常量临时对象.

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

这篇关于通过引用传递匿名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆