c++ - When to return T&& from a non-template and non-member function -


please note there previous answers concerning template functions or member functions question non-template non-member functions. std::move() returns t&&, example template function.

is there ever reason use t&& return type non-template , non-member function, t arbitrary type?

for example when ever use following?

t&& fn() { .... return .... } 

i have seen examples used in examples, developer misunderstood move semantics , should have returned value , taken advantage of nrvo.

suppose have particle system. want implement pool of particles. means going want recycle same particles on , on again, reuse resources, want pass around rvalues.

now, suppose our particles have short life time, want happen when "expire" (like incrementing integer x) still want recycle them. now, suppose want able specify x. but, do?

on move, want able call function increment variable, variable must fluctuate. wouldn't want put destructor because involve either templates derive exact function call @ compile time or need std::function or function pointer refer function inside particle, wasting space. want able take in expiring value, action, , forward it. in other words, want outgoing-move side effect on conversion lvalue rvalue.

it matter on action it--on lvalue rvalue conversion or on receiving particle operator= or operator(). either when object receives value or when take rvalue in. suppose want many different types of objects--do want write 5 or more different move functions each of 5 different classes, or perhaps should parameterize on types external templated function?

how else this? you're still going use std::move() inside object, want couple function external object, because represent side effect move.

coliru: http://coliru.stacked-crooked.com/a/0ff11890c16f1621

#include <iostream> #include <string>  struct particle {     int i;     };  template <typename t> t&& move( t& obj,  int (*fn)(int) , int& ) {     = fn(i);     return(std::move(obj)); }  int increment(int i) { return i+1; }  int main() {     // have object pool want optimize moving instead of creating new ones.     // we'll use rvalue semantics can "inherit" lifetime instead of copying.     particle pool[2000];      // fill "particles".     (auto = 0; < 2000; ++i) {         pool[i].i = i;         }      // perform moves side effects.     int j = 0;     (auto = 0; < 1999; ++i) {         pool[i+1] = move<particle>(pool[i], &increment, j);         std::cout << "moves performed: " << j << '\n';     }  } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -