Hunsu
Hunsu

Reputation: 3401

How to initialize a class member reference to the empty string in the default constructor

How can I initialize a class member reference to the empty string ("") in this default constructor.

class Document {
    string& title;
    string* summary;

    Document() : title(/*what to put here*/), summary(NULL) {}
};

Upvotes: 0

Views: 1032

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27548

There is no sensible way to do this. A reference must refer to an existing object (an ever better way to put it would be that a reference is the existing object), and the std::string that would be constructed in the initialiser list from "" would be destroyed after the constructor has finished, leaving you with undefined behaviour on every attempt to use your member variable.

Now, I said "no sensible way". There are hacks to achieve what you want, of course, e.g.:

// bad hack:
std::string &EmptyStringThatLivesForever()
{
    static std::string string;
    return string;
}

class Document {
    string& title;
    string* summary;

    Document() : title(EmptyStringThatLivesForever()), summary(NULL) {}
};

But I doubt that such a trick would survive any serious code review.

The real solution is to get rid of the reference:

class Document {
    string title;
    string* summary;

    Document() : title(""), summary(NULL) {}
};

Upvotes: 3

Related Questions