Mixing reference and value behavior in operator[]

I need "double" behavior from operator[], sometimes it must return a new instance variable (aka "temporary") and sometimes a reference to another variable so that = assignment can be used on the result.

var &getItemAt(int i) {} var &operator[] (int i) { if (this->isArray()) { return getItemAt(i); } var result = "undefined"; return result; <-- Error: attempt to return a reference to a local variable } var a = 123; // var can be a number, array, string or 'undefined' var b; b.setType("array"); b.push("one", "two", "three"); b[1] = "new value"; // needs to be var& for the assignment to work

If I attempt to declare like this (without &):

var operator[] (int i) {

the assignment to b[1] = ... will do nothing (in fact it will assign to a temporary variable, which is a copy of the one from the array found at index position 1 and holding the value "two".

But if I declare var & operator = the array semantics works perfectly, but I cannot return undefined or other temporary var.

How to mix both behavior into one?

-------------Problems Reply------------

You could return a reference to a static variable:

var &operator[] (int i) {
if (this->isArray()) {
return getItemAt(i);
static var result = "undefined";
return result;

This variable will exist until program termination, so won't dangle.

This is exactly the kind of thing that boost::optional and std::experimental::optional aim to address.

There are few solutions, althought 'static' will work for some cases, if you want to write to the returned newly created object, you will need to garbage collect it later. So the 'undefined' variable is allocated, rooted in the GC and then freed by the GC during it's memory deallocation turn.

You can also declare a wrapper class that would represent both data or a reference when needed and return that from the funtion, but then again you need to think how the allocated data shall bee freed, may be by reference counting.

Category:c# Views:0 Time:2019-02-09

Related post

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.142 (s). 11 q(s)