开发者

const string vs. #define

i need to share some strings in my c++ program. should i use #define or const string? thanks

mystring1.h

#define str1 "str1"
#define str2 "str2"    

Or

mystring2.h

extern const string s开发者_Python百科tr1;  
extern const string str2;  

mystring.cpp

const string str1 = "str1";  
const string str2 = "str2";


Prefer the second option. If you use the first option (preprocessor), you are limiting your flexibility with the object.

Consider the following... You won't be able to compare strings this way:

if (str1 == "some string")
{
    // ...
}


If it is C++ instead of C, you should really use some variable instead of a preprocessor macro. The former is clearer than the latter. Furthermore, if you use C++17, you can use inline variables:

inline const std::string str = "foobar";

or

// constexpr is implicitly inline
constexpr char str0[] = "foobar";
constexpr const char* str1 = "foobar";
constexpr std::string_view str2 = "foobar";

This is also clearer than using extern and can be used in header-only APIs as well.


If it's C++, you should use the C++ Standard Library's std::string. It's much more clear than a preprocessor macro, it will have a single location in memory when it's defined, and it has all the extra functionality of std::string instead of only pointer comparisons as is the case with the implicit const char* that are created with a preprocessor macro.


To take OO advantage of c++, I would say use struct/class.

header:

struct Constants {
    static const string s1;
    static const string s2;
};

cpp:

const string Constants::s1 = "blah1";
const string Constants::s2 = "blah2";

To reference:

cout << Constants::s1 << endl;


If you don't have to use the preprocessor don't!

If these strings are needed in a resource editor or a manifest or something you might have to.


You could also just use a const char* string for constant data and not a string object, since the object will need to be initialised at the start of the program with the constant data anyway. Do this if you're not going to be doing much with strings but just displaying them or printing them out as is.

So:

extern const char * str1;

and

const char * str1 = "str1";


I would suggest use of functions.

extern const std::string& str1();
extern const std::string& str2();

This gives you more flexibility in how you get those strings in the .cpp file.


Also consider the issue of non-POD static construction and destruction order, as described in the Google C++ style guide.

An alternative is to use:

const char str1[] = "str1";
const char str1[] = "str2";
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜