c++ - Passing r-value as non-const reference (VS warning C4239) -


what wish (using c++ lambda) effectively:

std::vector<mytype> getthearray () {return something;}  const auto dosomething = [](std::vector<mytype> & array) {      //some processing involves either sorting 'array' or setting temporary flags on items };  dosomething (getthearray ()); 

this appears disallowed in standard c++ because rvalue cannot passed non-const reference.

my questions:

1) there way using type-cast or obliged create temporary variable store results of getthearray ()?

2) there reason why disallowed in c++?

please note 'something' returned 'getthearray' array constructed on fly, not stored value.

it seems comments want take vector, modify destructively (in sense original state cannot reset) , use result internally. , want work efficiently both lvalues , rvalues.

the next question whether in case of lvalue, code holds original container needs after function call has completed, , if needs original state of vector or not. depending on answers have different solutions:

the caller holding lvalue not use anymore after call

(or alternatively, caller holding lvalue needs original state)

this simplest case. function should take container value. if caller has lvalue, can std::move avoid copy (it not care object anymore) or copy might more expensive leaves original container untouched.

if function called rvalue copy either elided or transformed cheap implicit move.

the caller holding lvalue not need original state, needs container

this case hard one, , need provide 2 overloads same function (or lambda), 1 taking lvalue used caller , different taking rvalue-reference case caller hands temporary. in both cases binding cheap. while requires more code, can implement 1 overload in terms of other:

rtype f(std::vector<data> & );   // lvalues rtype f(std::vector<data> && v)  // rvalues    { return f(v); }              // v lvalue here 

the fact doing lambdas might make more complicated, not much.


Popular posts from this blog

How to calculate SNR of signals in MATLAB? -

c# - Attempting to upload to FTP: System.Net.WebException: System error -

ios - UISlider customization: how to properly add shadow to custom knob image -