www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Destructor called on null objects?

reply ilitirit <ilitirit_member pathlink.com> writes:
Is this standard behaviour?

void main()
{
class Foo
{
this()
{
throw new Exception("Exception thrown in constructor");
}
~this()
{
printf("Destructor was called");
}
}

Foo foo = null;

try
{
foo = new Foo();
foo ? printf("Foo is not null\n") : printf("Foo is null\n");
printf("After instantiantion");
}
catch(Exception e)
{
printf("%.*s\n", e.toString());
// foo == null ? <x> : <y> <- causes 'Access Violation'
foo ? printf("Foo is not null\n") : printf("Foo is null\n");
}
}

Output:
Exception thrown in constructor
Foo is null
Destructor was called
Dec 30 2004
parent "Charles" <no email.com> writes:
People need to be forced to untabify all code they post!

 // foo == null ? <x> : <y> <- causes 'Access Violation'
needs to be ' foo is null' , or 'foo === null'. This was a gotcha for me at first as well, === is testing identity and == is testing equality. Charlie "ilitirit" <ilitirit_member pathlink.com> wrote in message news:cr30fo$2kbi$1 digitaldaemon.com...
 Is this standard behaviour?

 void main()
 {
 class Foo
 {
 this()
 {
 throw new Exception("Exception thrown in constructor");
 }
 ~this()
 {
 printf("Destructor was called");
 }
 }

 Foo foo = null;

 try
 {
 foo = new Foo();
 foo ? printf("Foo is not null\n") : printf("Foo is null\n");
 printf("After instantiantion");
 }
 catch(Exception e)
 {
 printf("%.*s\n", e.toString());
 // foo == null ? <x> : <y> <- causes 'Access Violation'
 foo ? printf("Foo is not null\n") : printf("Foo is null\n");
 }
 }

 Output:
 Exception thrown in constructor
 Foo is null
 Destructor was called
Dec 31 2004