mardi 29 décembre 2015

Top-level or low-level constness or neither?

I'm working through the C++ Primer and if I understand it correctly:

  • Top-level constness applies to the object itself.
  • Low-level constness means that the the referenced object is const which makes the referenced object top-level const.
// A plain int.
int i {0};

// Top-level const ints.
const int ci {42};
const int ci2 {0};

// A low-level pointer to const int.
const int * pci {&ci};

// Low-level, because the referenced object can't be changed.
*pci = 0; // error

// But not top-level, because it can be changed to point to another object.
pci = &ci2; // fine

// This is both top-level and low-level const
// because both the pointer and the object it
// points to are const:
const int * const cpci {&ci};
*cpci = 0;   // error
cpci = &ci2; // error

Now the question. Is there a naming convention for a constness which is neither top-level nor low-level? I.e. the pointer itself is not const but it points in a constant way to a non-const object? Or is this a special case of low-level constness? Example:

int i {0];
int j {42};

// The following pointer is not const itself.
// The object it's pointing to is not const but
// it can't be manipulated through the pointer.
const int * pci {&i};
*pci = 42; // error

// All these are fine:
++i;
pci = &j;
++j;

*pci = 42; // error as above

Aucun commentaire:

Enregistrer un commentaire