return string from inside if block => Segmentation Fault: 11

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jun 1 10:29:08 PDT 2015


On 6/1/15 1:19 PM, Robert M. Münch wrote:
> On 2015-06-01 17:06:27 +0000, Kapps said:
>
>> Chances are very good that it's the code within the if statement,
>> classes are null by default, you're checking if null isEmpty, thus
>> getting a segfault.
>
> Isn't the construtor of the contained types run when the class is
> constructed? Or do I need to explicitly initialize the contained types
> on my own?

No, you must explicitly intialize. Classes are ALL reference types in D, 
no in-situ placement of classes (without a lot of heavy lifting):

class C
{
}

class D
{
    C c; // this is a *reference* to a C object, equivalent to C* c if 
you were using C++
    this()
    {
       assert(c is null); // not yet initialized!
       c = new C; // now the ctor is run.
    }
}

Note that c is initialized, to null :) So an initialization does happen, 
but not what you expected. This whole thing avoids the requirement of 
initialization of members before the ctor runs (like in C++).

-Steve


More information about the Digitalmars-d-learn mailing list