Which one to use Value vs std::string in cocos2d-x V3 C++?

426 Views Asked by At

According to http://www.cocos2d-x.org/wiki/Value,

Value can handle strings as well as int, float, bool, etc.

I'm confused when I have to make a choice between using

std::string

or

Value

In what circumstances should I use Value over std::string, and vice versa??

1

There are 1 best solutions below

0
Vidur On

I think you have misunderstood the Value object. As written in the documentation you linked to:

cocos2d::Value is a wrapper class for many primitives ([...] and std::string) plus [...]

So really Value is an object that wraps a bunch of other types of variables, which allows cocos2d-x to have loosely-typed structures like the ValueMap (a hash of strings to Values - where each Value can be a different type of object) and ValueVector (a list of Values).

For example, if you wanted to have a configuration hash with keys that are all strings, but with a bunch of different values - in vanilla C++, you would have to create a separate data structure for each type of value you want to save, but with Value you can just do:

unordered_map<std::string, cocos2d::Value> configuration;

configuration["numEnemies"] = Value(10);
configuration["gameTitle"]  = Value("Super Mega Raiders");

It's just a mechanism to create some loose typing in C++ which is a strongly-typed language.

You can save a string in a Value with something like this:

std::string name = "Vidur";
Value nameVal = Value(name);

And then later retrieve it with:

std::string retrievedName = nameVal.asString();

If you attempt to parse a Value as the wrong type, it will throw an error in runtime, since this is isn't something that the compiler can figure out.

Do let me know if you have any questions.