Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this return a const X* const pointer within a const method?

Tags:

c++

pointers

I got troubles undertanding the following error:

Error 1 error C2440: '=' : cannot convert from 'const X<...> *const ' to 'X<...> *const '

I am trying to use a pointer to const pointer to keep track of a Node during a tree traversal:

bool IsValid() const
  {
    X* const* previousNode = new X*;
    return this->IsValid(previousNode);
  }

  bool IsValid(X* const* previousNode) const
  {
    ...
    if (!*previousNode)
      *previousNode = this; // Error
    ...

    return true;
  }

Why is this is a const X* const type and cannot be used as a *Const * ?

As the method is a const method, my understanding is that it protects the object itself of being modified. Then why does the compiler try to enforce the constness of a pointer to pointer returning this?

I have not been able to find an answer to this question using the search engine of stack overflow.

Thank you for your answers.

Here is the finale code I finally used if I can be a use for someone:

bool IsValid() const
  {
    std::unique_ptr<const BST*> previousNode = std::unique_ptr<const BST*>(new const BST*);
    *previousNode = nullptr;
    return this->IsValid(prevNode);
  }

bool IsValid(std::unique_ptr<const BST*>& previousNode) const
{
  // Recurse on left child without breaking if not failing
  if (this->leftChild &&!this->leftChild->IsValid(previousNode))
    return false;

  // First node retrieved - assign
  if (!*previousNode)
    *previousNode = this;
  // Previous data does not compare well to the current one - BST not valid
  else if (!Compare()((*previousNode)->data, this->data))
    return false;

  // Set current node
  *previousNode = this;

  // Recurse on right child
  if (this->rightChild && !this->rightChild->IsValid(previousNode))
    return false;

  return true;
}

Just playing with template and simple data structure. Thank you for your answers.

like image 308
Jeulin-L Michael Avatar asked Mar 12 '23 19:03

Jeulin-L Michael


2 Answers

Let's start simple:

  • a const X* is a pointer to a constant X
  • a const X* const is a constant pointer to a constant X
  • a const X* const*is a pointer to a constant pointer to a constant

Back to your problem:

  • X* const* previousNode is a pointer to a constant pointer to an X
  • so *previousNode is a constant pointer to an X
  • but *previousNode = ... tries to assign something to this constant pointer. It's not possible, the pointer is constant !
like image 180
Christophe Avatar answered Mar 20 '23 12:03

Christophe


The signature of the IsValid method specifies (by using const), that this is a constant object, i.e. its type is const X*. Changing the type of previousNode to const X** should solve your problem.

like image 27
majk Avatar answered Mar 20 '23 11:03

majk