~= call copy ctor?

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 22 13:38:18 PDT 2012


On Sunday, July 22, 2012 20:45:05 monarch_dodra wrote:
> AFAIK, there are no invalid objects in D*. structs don't have
> default constructors, because they all have a compile time "init"
> value which they are filled with when
> "emptied"/"moved"/"cleared". Ergo, even after being "destroyed",
> they are still valid.
> 
> Arrays are set to a null slice.
> 
> Pointers and class references are set to null.
> 
> To check a class reference, then "if(instance is null)" should do
> what you want BTW.
> 
> *Provided you don't go out of your way to give them an invalid
> state, of course.

Nothing in D is in an invalid state as long as you place nice, but it's 
perfectly possible to put an object in an invalid state if you try.

int i = void;

will make i garbage. It avoids the initialization and is therefore an 
optimization technique, but by using it, you do get a variable which is an an 
invalid state.

Calling clear on a class object puts it in an invalid state. It calls its 
finalizer and zeroes out its vtbl. It's _not_ null, and using it will likely 
result in a segfault (some non-virtual stuff may still work, but anything 
virtual will cause a segfault because of the zeroed out vtbl).

Calling clear on pretty much everything else is safe, since it generally just 
sets everything else to null without doing any kind of destruction or cleanup. 
The on exception would be structs, and with them, they get put in their init 
state if they're on the stack, and if they're on the heap, the pointer to them 
gets set to null. The struct itself is untouched. But for classes, it's _not_ 
safe. The object _does_ get put in an invalid state.

Stuff like initializing to void or calling clear on an object are really only 
there so that you have more fine-grained control when you really need it, and 
they come with definite responsibility when you do use them, because you're 
telling the language that you don't need its full protection and that you know 
what you're doing. They really shouldn't be used in your average D program.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list