Question

I'm having this strange issue with my code where it seems as if the compiler is implicitly casting my argument to another type. However when I tag the constructor as explicit, it didn't seem to fix the issue.

I have this in my unit test

JsonValue stringItem("test");
CHECK(stringItem.type() == JsonValue::Type::String);

This fails with the result

4 == 3

These are what the constructors look like...

JsonValue::JsonValue()
 : mType(Type::Null) {
}

JsonValue::JsonValue(bool ab)
 : mType(Type::Boolean) {
    mData.b = ab;
}

JsonValue::JsonValue(int ai)
 : mType(Type::Int) {
    mData.i = ai;
}

JsonValue::JsonValue(std::uint32_t aui)
 : mType(Type::UnsignedInt) {
    mData.ui = aui;
}

// It should be using this constructory
// but mType is not getting set to Type::String
JsonValue::JsonValue(const std::string &astr)
 : mType(Type::String) {
    mData.str = new std::string(astr);
}

As I mentioned before, tagging JsonValue(bool) as explicit didn't fix the issue. I also compiled with -Wconversion without warnings

Enum looks like this

enum Type {
            Null = 0,
            Object,
            Array,
            String,
            Boolean,
            Int,
            UnsignedInt
         };
Was it helpful?

Solution

You need to be explicit about the argument to the constructor:

JsonValue stringItem(std::string("test"));

What is happening is that you are getting an implicit conversion from const char* to bool, because this is a conversion between built-in types, and a better match than the conversion from const char* to std::string, which is a conversion involving a built-in type.

Alternatively, you can add a constructor that takes const char* and stores a string internally. This is a better option because it avoids the easy to make error you encountered:

JsonValue::JsonValue(const char* astr)
 : mType(Type::String) {
    mData.str = new std::string(astr);
}

Note that on the surface these seems to be no reason to store a dynamically allocated string. This probably adds unnecessary complications.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top