What's wrong with const?

前端 未结 12 2229
無奈伤痛
無奈伤痛 2021-01-31 12:06

What are the known shortfalls of const in C++ and C++0x?

12条回答
  •  渐次进展
    2021-01-31 12:32

    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.

提交回复
热议问题