Question

I'm attempting to write unit tests in which we call the constructor to a generic class in the form:

void testConstructor() {
    int argc = 2;
    ACE_TCHAR* argv[] = {"Input1", "Input2"};
    MyClass *myClass = new MyClass(argc, argv);
    /**processing**/
}

Think of ACE_TCHAR* the same as char*. The code above results in

warning: deprecated conversion from string constant to ‘ACE_TCHAR*’

I have also tried:

void testConstructor() {
    int argc = 2;
    ACE_TCHAR* argv[2];
    argv[0] = "Input1";
    argv[1] = "Input2";
    MyClass *myClass = new MyClass(argc, argv);
    /**processing**/
}

Which results in the same error.

I read online somewhere that this could be mitigated by using

const ACE_TCHAR* argv[] = {"Input1", "Input2"};

But then the compile fails because of the function signature.

Edit: I'm not allowed to modify the 3rd party code, I'm only writing unit tests for it.

Any ideas?

Was it helpful?

Solution

A string constant is, as the name says, a constant. So to make the warning go away, the proper solution would indeed be to turn the pointer into a const pointer.

If that cannot be done, you can explicit typecasts

ACE_TCHAR* argv[] = {const_cast<ACE_TCHAR*>("Input1"),
                     const_cast<ACE_TCHAR*>("Input2")};

or assign the strings to non-constant char arrays first

char input1[] = "Input1";
char input2[] = "Input2";
ACE_TCHAR* argv[] = {input1, input2};

OTHER TIPS

The type of a string literal is "array of const char". By the implicit array-to-pointer conversion, you can use this to initialize or assign to a const char *.

But there is a special rule, that a string literal can also be implicitly converted to a char * (without const). This rule exists for compatibility with old C code, where char * str = "string literal" was a common idiom. Using this is dangerous, because modifying the pointed to character array through that pointer causes undefined behavior (i.e. your program may crash, or anything else can happen). For that reason the construct is deprecated and your compiler warns you about it.

To create valid data you can pass on as non-const character pointers, you can use

const int argc = 2;
ACE_TCHAR argv0[] = "Input1";
ACE_TCHAR argv1[] = "Input2";
ACE_TCHAR* argv[] = { argv0, argv1 };
MyClass *myClass = new MyClass(argc, argv);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top