structs holding on to reference data by pointer

Maxim Fomin maxim at maxim-fomin.ru
Thu Oct 31 09:23:05 PDT 2013


On Thursday, 31 October 2013 at 15:11:48 UTC, Daniel Davidson 
wrote:
> The following seems to work, but feels like luck. When foo 
> returns rc should be taken off the stack. If I recall, in C++ 
> something like this would crash, but why not here?

This ineed runs by luck. In C++ it would not necessarily crash, 
but it is UB like in D.

You can workaround issue by:

import std.stdio;

struct S
{
	int[] data;
	const this(this) { S *s = cast(S*)&this; s.data = s.data.dup; }
}

struct SS
{
	const S s;
}

void main()
{
	S s1, s2;
	s1.data = s2.data = [0,1];
	s1 = s2;
	s2.data[0] = 1;
	writeln(s1.data);
}

but this breaks constness and penalty is that function with casts 
cannot be run in safe code. (However in this case there is no 
logical mutation because 's' keeps its value. Probably self 
modifying const postblits should be allowed with restriction that 
it is programmer duty to ensure that const object is duplicated, 
but not mutated - at least judging by postblit definition it is 
reasonable assumption  with some degree of confidence.)


More information about the Digitalmars-d-learn mailing list