Discussion on error reporting analysis of const variable assignment

  • 2020-04-02 03:08:23
  • OfStack

Assignment from variable to constant is a valid C++ syntax convention,

Smooth from char to const char;
But from char ** to const char ** the compiler will report an error:


error: invalid conversion from `char**' to `const char**'

Example:


int main(int argc, char *argv[])
{
  char a = '1';
  const char b = a;

  char * a2 = "12345";
  const char * b2 = a2;

  char** a3 = NULL;

  //const char** b3 = a3; //error
   char** const c3 = a3; //ok
   char* const * d3 = a3; //ok
}

The reason:

Const char** b3 means that the pointer to b3 can be changed to point to another address.
Both b3 and a3 are unqualified, but b3 points to an object of type pointer to const char,
Pointer to char the object type pointed to by a3 is pointer to char. The two are incompatible types.
Does not meet the requirement that two operands must point to a compatible type, so the assignment is illegal.
See resources 1 for a more detailed explanation;

Char ** const c3 = a3; Correct, because const restricts the address change of c3 pointer, that is, it points to a3, can no longer change to other pointer; This limits the potential problems with pointer address changes;

In this case, of course, a cast can resolve the compilation error:


    const char** b3 = const_cast<const char**>(a3); // ok

But it is difficult to troubleshoot the code after conversion;

Potential problems with casting

See the following example:


class Foo {
public:
 Foo(){
   i = 1;
 }
 void modify(){// make some modification to the this object
   i = 2;
 } 
 void print() const {
   cout << "Foo_i:" << i << endl;
 }
private:
 int i;
};

//Demonstrate potential hazards
//error: invalid conversion from `Foo**' to `const Foo**'
/////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
  const Foo x;
  Foo* p;

  //const Foo ** q = &p; //q now points to p; this is (fortunately!) an error
  const Foo ** q = const_cast<const Foo **>(&p); 
  *q = &x; // p now points to x
  p->modify(); // Ouch: modifies a const Foo!! 
  x.print(); // print: Foo_i:2
  return 0;
}

We've defined a constant Foo, the constant Foo method will always print out to be 1;

Foo** to const Foo**

Let the compiler pass with a strong spin,

The final x.print() is 2; Such potential hazards are hard to detect in formal project code;

It's hard to think of a const object that can be changed;

The above is all the content of this article, I hope you can enjoy it.


Related articles: