Const initialization issue, looking for solution

Jakob Ovrum jakobovrum at gmail.com
Wed May 29 05:36:18 PDT 2013


Consider the following example:

http://dpaste.dzfl.pl/a0595ddf
----
// Can throw, and we want to catch
int createTheVar();

// Can also throw, but we don't want to catch it here
int transform(int a);

int foo()
{
	const(int) i;

	try
	{
		i = createTheVar(); // Clearly not allowed
	}
	catch(Exception e) // For demo purposes
	{
		// Exception handling code
	}

	return transform(i);
}
----
I need to be able to catch an exception that may have been thrown 
during the initialization of `i`, but still have `i` be const. I 
can't omit the variable because I *don't* want to accidentally 
catch anything that transform() may have thrown.

Note that the simple type const(int) is an example. This is 
actually in highly generic code and the type may have mutable 
indirection.

Here's the real-world code:
https://github.com/JakobOvrum/LuaD/blob/master/luad/conversions/functions.d#L86

The particular problematic type I happened to encounter for 
RetType is the const(CacheInfo)[5] return type of 
core.cpuid.dataCaches:
http://dlang.org/phobos/core_cpuid.html#.dataCaches

Specifics aside, I believe this is a very general problem.

----
Of course, if D had well-defined, local flow analysis like many 
other modern languages (e.g. C#), this code would not have to be 
rejected. I think that's a discussion for the future though; 
right now it would be nice to have a workable, general 
solution/workaround to the issue of initializing const/immutable 
variables in try-blocks.

Any help is much appreciated.


More information about the Digitalmars-d mailing list