I'm writing a Cocos2D-X game where the player, enemies and other characters store their attributes in a CCMutableDictionary
, which is somewhat of a decorator class for std::map<std::string, CCObject*>
. A value in the dictionary can be accessed via the CCMutableDictionary::objectForKey(const std::string& key)
method.
Now, in a header file included by many of my .cpp files, I've got a few const char * const
strings for accessing values in the dictionaries, like this:
// in Constants.h
const char* const kAttributeX = "x";
const char* const kAttributeY = "y";
// in a .cpp file
CCObject* x = someDictionary->objectForKey(kAttributeX);
So, correct me if I'm wrong, but std::string
's copy constructor is being called and a temporary std::string
is on the stack every time I call one of the above objectForKey
methods using a const char* const
, right?
If so, I feel that it would be more efficient at runtime if those constant attribute keys were already std::string
objects. But how do I do that the right way?
Defining them in the Constants.h file like the following compiles fine, but I have a feeling that something just isn't right:
// in Constants.h
const std::string kAttributeX = "x";
const std::string kAttributeY = "y";
My apologies if this question has already been asked. I couldn't seem to find the exact answer I was looking for here on StackOverflow.
#include <string. h> Inclusion of <string> In C++ is recommended when the program needs to use string.
Just like the other data types, to create a string we first declare it, then we can store a value in it. cout << "This is a string." << endl; In order to use the string data type, the C++ string header <string> must be included at the top of the program.
To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
const is compile time. When you use const string you end up not using space for this variable during run time. The compiler uses this value in a way not dissimilar to a macro. When you don't use const string it acts like any other variable and occupies additional space during run time.
The code you wrote is perfectly fine, at least as you only #include
the Constants.h
file in only one source file. If you use the header file in multiple source files, you will have the same variables defined multiple times. The correct use of constants in header files are to split them into a header (Constants.h
) which contains the declarations of the variables, and a source file (Constants.cpp
) which contains the definitions of the variables:
The header file:
#ifndef CONSTANTS_H
#define CONSTANTS_H
extern const std::string kAttributeX;
extern const std::string kAttributeY;
#endif
The source file:
const std::string kAttributeX = "x";
const std::string kAttributeY = "y";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With