Saturday, 15 June 2013

c++11 - How can a function in C++ return either a value or a reference with minimal copying? -



c++11 - How can a function in C++ return either a value or a reference with minimal copying? -

i have function delegates 2 others, returning either reference or value depending on runtime condition:

x by_value() { ... } const x& by_reference() { ... } ?? foo(bool b) { if (b) { homecoming by_value(); } else { homecoming by_reference(); } }

i'd take homecoming type of function callers induce minimal copying; e.g.:

const x& x1 = foo(true); // no copies const x& x2 = foo(false); // no copies x x3 = foo(true); // no copies, 1 move (or 0 via rvo) x x4 = foo(false); // 1 re-create

in cases except last, there shouldn't need (based on runtime behavior) re-create homecoming value.

if homecoming type of foo x, there re-create in case 2; if homecoming type const x&, cases 1 , 3 undefined behavior.

is possible, via returning sort of proxy, ensure above uses have minimal copies?

explanation: since there's been important pushback of form "you're doing wrong", thought i'd explain reason this.

imagine have array of type t or function<t()> (meaning elements of array either of type t, or they're functions returning t). "value" of element of array, mean, either value or homecoming value when function evaluated.

if get_value_of_array(int index) returns value, in cases array contains element, i'm forced copy. i'm trying avoid.

further note: if reply is, "that's impossible", that's fine me. i'd love see proof of this, though - ideally of form "suppose there type proxy<x> solved problem. then...`

what looking sum-type (that is, type possible values "the possible x values plus possible x const& values").

in c++, these called variant. these implemented tag plus appropriately sized , aligned array, , hold 1 value @ runtime. alternatively, implemented dynamic allocation , classic visitor pattern.

for example, boost.variant, declare function homecoming boost::variant<x, x const&> (live example):

boost::variant<x, x const&> foo(bool b) { if (b) { homecoming by_value(); } else { homecoming by_reference(); } }

c++ c++11

No comments:

Post a Comment