const after initialization / pointers, references and values

Vicente via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 22 14:18:50 PDT 2014


On Friday, 22 August 2014 at 20:12:39 UTC, Wyatt wrote:
> I poked it a bit and came out with this.  I _think_ it's 
> working as expected:
...
>         auto ref opSlice(){return nodes[];};
...
> -Wyatt

Assuming it's working as expected, that is exactly what I was 
looking for!
But the following code shows that at some point data gets copied. 
By the way, neither works what I've posted previously.
In any case, thank you very much Wyatt.

Regards,
   Vicente.

@safe:
import std.stdio;
import std.string;

struct Node { Node[] block; uint num = 0; };
/* immutable */ Node[] default_nodes = [ {num:3}, 
{block:[{num:4}]}, {num:6} ];

class NodeProvider{
	private /* const */ Node[] nodes;
	private Node[] tmp_nodes;

	private void parse_file(char[] file_name){
		tmp_nodes.length=1; tmp_nodes[0].num=5;
	}

	this(){ nodes = default_nodes; }
	this(char[] file_name){
		parse_file(file_name);
		nodes = tmp_nodes;
	}

	auto ref opSlice(){return nodes[];};
}

@system: // for writeln
int main(char[][] args){
	NodeProvider np;

	if(args.length==2) np = new NodeProvider(args[1]);
	else               np = new NodeProvider();

	// if they are real references this will modify the source data
	foreach(node_ref; np) node_ref.num = 101;
	// and will print all 101
	foreach(node_ref; np) writeln(node_ref.num);
	// but it prints unmodified 3, 0 and 6

	return 0;
}


More information about the Digitalmars-d mailing list