Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ equivalent of Java static final String

Tags:

c++

I often need to define string constants associated with a class. Examples would be XML attributes, default filenames and many more.

In Java I would simply define something like

public static final String KEY = "attribute";

inside the class or interface.

In C++ the following would not compile:

class Example {
public:
    static const std::string KEY = "attribute";
}

Instead, I would have to write:

class Example {
public:
    static const std::string KEY;
}

const std::string Example::KEY = "attribute";

This is something I absolutely want to avoid because of its redundancy and verbosity.

The best solution I found so far is to use functions:

class Example {
public:
    static std::string KEY() const { return "attribute"; }
}

This also provides some encapsulation and flexibility. However it might seem a bit weird to use a function just to define a constant.

So my question is, does this solution have major drawbacks and if yes, what are better alternatives?

like image 819
Frank Puffer Avatar asked Jul 03 '26 21:07

Frank Puffer


1 Answers

In c++03, your best option is to use a function the way you are using, and this is awkward. The only thing is, why are you returning std::string and paying it's construction price, when you can return const char* const free of charge.

If, for some reason, you really have to have const std::string (again, it runs against my whole experience, so you might want to reconsider) following code works best in terms of efficiency (your current version calls std::string constructor on every call!):

class Example {
public:
    static const std::string& key() {
       static const std::string the_key = "That's my key!";
       return the_key;
    }
}

In c++11, you have several options, of which I find the best a constexpr:

class Example {
public:
    static constexpr const char* const KEY = "TheKey";
}

The other option is in-place initialization of your const string, but why pay the price of it?

class Example {
public:
    static const std::string KEY = "TheKey";
};
like image 133
SergeyA Avatar answered Jul 05 '26 12:07

SergeyA