What are the known shortfalls of const in C++ and C++0x?
Another problem that has not been mentioned yet is the possibility for a badly designed interface to subvert const (even in the absence of casts).
Example:
class TreeNode {
public:
TreeNode& getParent() const { return *parent_; }
TreeNode& getLeft() const { return *left_; }
TreeNode& getRight() const { return *right_; }
private:
//TreeNode has a pointer to the Tree to enable navigation of the tree.
//Assume that other design constraints mean that this must be a pointer
//rather than a reference.
TreeNode* parent_;
TreeNode* left_;
TreeNode* right_;
};
//This function demonstrates the ability for const to be subverted.
TreeNode& remove_const(TreeNode const& toRemoveConstFrom) {
TreeNode& parent(toRemoveConstFrom.getParent());
TreeNode& leftChild(parent.getLeft());
TreeNode& rightChild(parent.getRight());
return &toRemoveConstFrom == &leftChild ? leftChild : rightChild;
}
The intransitive nature of const means that it is possible to have an interface where a non-const reference to an object can be obtained from a const reference to an object. This is something to be careful of when designing interfaces.