简体   繁体   English

const正确性和成员参考

[英]const correctness and member reference

I have the following class: 我有以下课程:

class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    { 
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};

Theoretically Fun can be const but I wonder if it is correct (logical constness) ? 从理论上讲, Fun可以是const,但我想知道它是否正确(逻辑常量 )?

Edit1 I added a very simplified Fun implementation. Edit1我添加了一个非常简化的Fun实现。 Edit2 Data has two GetInfo overloads: Edit2 Data具有两个GetInfo重载:

Info& Data::GetInfo();
const Info& Data::GetInfo() const;

const in this context means "does not modify the object", which is enforced by treating the implicit this as pointer-to-const. 在此上下文中, const表示“不修改对象”,这是通过将隐式this视为指向const的指针来实施的。 For this reason it is common to see overloads like 因此,通常会看到类似

Data       & getData();
Data const & getData() const;

This preserves the const ness of the calling context, and allows for modifying the Data when called in a non-const context. 这将保留const调用上下文的岬,并允许修改该Data在非const上下文中调用时。

In your case, you don't have a Info & Data::getInfo const; 就您而言,您没有Info & Data::getInfo const; (which would be rather suspect, where does const Data get a non-const Info from?) Fun is modifying the data_ member of DataBuilder . (这很让人怀疑,const Data从哪里获得非const Info ?) Fun正在修改DataBuilderdata_成员。

Aside: I would write the assignment as data.GetInfo() = newInfo; data.GetInfo() = newInfo; :我会将赋值写为data.GetInfo() = newInfo;

Fun is manipulating data. Fun在于操纵数据。 So it should not be able to be declared const . 因此, 不应将其声明为const The fact that you are able to do that is that apparently, data.GetInfo is declared const , yet returns a reference through which you can manipulate it's internal state. 做到这一点的事实是,很显然, data.GetInfo声明const ,又返回,通过它你可以操纵它的内部状态的参考。 That's bad programming. 那是不好的编程。

So no, this is not correct. 所以不,这是不正确的。 Even in theory, Fun should not be const because it is not. 即使从理论上讲, Fun也不应为const因为它不是。 It is manipulating internal state. 它正在操纵内部状态。 The fact that it could be is due to bad coding. 可能是因为编码错误。 Fix that. 解决这个。 const -correctness is something that cannot be done halfheartedly. const -correctness是不能专心做的事情。 You do it, or you don't. 你做,或者你不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM