我试图在一个真正const的类上有一个const操作-它不会改变类指向的数据。

例如:

class Node{
public:
    int val;
};
class V{
public:
    Node * node; //what is the change that is needed here?
    void const_action()const{
        node->val=5; //error wanted here
    }
    void action(){
        node->val=5; //error is not wanted here
    }
};
有帮助吗?

解决方案

您可以使用模板在指针上强制执行Const正确性,而无需更改类别的含义或执行:

    template <typename T>
class PreseveConstPointer
{
    T *t_;
public:
    PreseveConstPointer(T *t = nullptr)
        : t_(t)
    {
    }
    PreseveConstPointer<T> * operator=(T *t)
    {
        t_ = t;
        return this;
    }
    T* operator->()
    {
        return t_;
    }
    T const * operator->() const
    {
        return t_;
    }
    T * data()
    {
        return t_;
    }
};
class Node{
public:
    int val;
};
class V{
public:
    PreseveConstPointer<Node> node;
    V()
    {
        node = new Node;
    }
    ~V()
    {
        if(node.data())
            delete node.data();
    }
    void const_action()const{
        node->val=5; // You will get an error here
    }
    void action(){
        node->val=5; // No error here
    }
};
.

其他提示

const 在函数声明之后,函数不允许更改任何类成员(标记的成员除外 mutable).

由于您的代码不会更改任何类成员,并且只更改对象 node 指向,两个函数都会编译。

AFAIK没有办法阻止这种情况。如果你标记 node const, ,两者都不会编译。

你很困惑 Node* constNode const*.

一个[不幸?]这里使用间接的副作用是 const指针成员的ness与实际无关 Node 你在做手术。

如果您不需要该成员是指针,那么这很容易:

class V
{
public:
    Node node;

    void const_action() const
    {
        node.val = 5; // error here
    }

    void action()
    {
        node.val = 5; // no error here
    }
};

然而,鉴于它的名字,我怀疑生活并不那么简单,你基本上是运气不好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top