开发者

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

I am parsing some text and it would make my life easier if i can use arrays are rvalues rather then defining it on their own line. I have done this

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

and

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

i tried

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

I can put additional things at the end of the line but not before. Do you guys have any ideas?


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

I find interesting the comment works well. I am not a lambda lawyer, but I believe that the code above is returning a pointer into a local variable, and that is undefined behavior, so even if that compiles that does not mean that it is correct.

As to what happens under the hood, my understanding is that the compiler transforms the lambda into a functor in a way similar to (note that this is a simplification taking into consideration that there are no captures, and the exact 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
   }
};


I'm not sure this is what you want, but you can do the following:

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

Note, that Microsoft compiler doesn't support it, but it is valid according to C++'03 Standard.


The only thing you can do in C++03 is encase the array in a struct/class. Then the whole object can be passed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜