数组作为单行上的右值,与C++2003配合使用

array as rvalue on single line which works with C++2003?

本文关键字:C++2003 单行 数组      更新时间:2023-10-16

我正在解析一些文本,如果我可以使用数组的右值,而不是在自己的行中定义它,这将使我的生活更轻松。我已经做了这个

 int a[]={1,2,3}; //its own line. Do not want

 func([]()->int*{static int a[]={1,2,3}; return a; }()); //It compiles but untested. It doesn't compile with 2003

我试过

 func(int []={1,2,3}); //but got a compile error bc this is simply illegal

我可以把额外的东西放在行的末尾,但不能放在前面。你们有什么想法吗?

func([]()->int*{int a[]={1,2,3}; return a; }()); //works well on C++0x.

我觉得有趣的是,评论效果很好。我不是lambda律师,但我相信上面的代码正在返回一个指向局部变量的指针,这是未定义的行为,所以即使编译了也不意味着它是正确的。

至于引擎盖下发生的事情,我的理解是编译器以类似于(注意,这是一种简化,考虑到没有捕获,确切的lambda:

struct __lambda {
   // no captures: no constructor needed, no member objects needed
   int* operator()() {        // returns int*, no arguments
      int a[] = { 1, 2, 3 };  // auto variable
      return a;               // return &a[0], address of a local object
   }
};

我不确定这是否是您想要的,但您可以执行以下操作:

  for ( int a[3] = {1, 2, 3}; func( a ), false; );

请注意,Microsoft编译器不支持它,但根据C++’03标准,它是有效的。

在C++03中唯一能做的就是将数组封装在结构/类中。然后可以传递整个对象。