Note that there are some explanatory texts on larger screens.

plurals
  1. POProper way to do const std::string in a header file?
    primarykey
    data
    text
    <p>I'm writing a Cocos2D-X game where the player, enemies and other characters store their attributes in a <code>CCMutableDictionary</code>, which is somewhat of a decorator class for <code>std::map&lt;std::string, CCObject*&gt;</code>. A value in the dictionary can be accessed via the <code>CCMutableDictionary::objectForKey(const std::string&amp; key)</code> method.</p> <p>Now, in a header file included by many of my .cpp files, I've got a few <code>const char * const</code> strings for accessing values in the dictionaries, like this:</p> <pre><code>// in Constants.h const char* const kAttributeX = "x"; const char* const kAttributeY = "y"; // in a .cpp file CCObject* x = someDictionary-&gt;objectForKey(kAttributeX); </code></pre> <p>So, correct me if I'm wrong, but <code>std::string</code>'s copy constructor is being called and a temporary <code>std::string</code> is on the stack every time I call one of the above <code>objectForKey</code> methods using a <code>const char* const</code>, right?</p> <p>If so, I feel that it would be more efficient at runtime if those constant attribute keys were already <code>std::string</code> objects. But how do I do that the <em>right</em> way?</p> <p>Defining them in the Constants.h file like the following compiles fine, but I have a feeling that something just isn't right:</p> <pre><code>// in Constants.h const std::string kAttributeX = "x"; const std::string kAttributeY = "y"; </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload