c ++在签名中使用const的含义

jbu*_*jbu 3 c++ const

请帮我理解以下签名:

err_type funcName(const Type& buffer) const;
Run Code Online (Sandbox Code Playgroud)

所以对于第一个const,这是否意味着Type的内容不能改变或者引用不能改变?

其次,第二个const是什么意思?我甚至都没有暗示.

在此先感谢,jbu

R S*_*hko 18

第二个const意味着可以在const对象上调用该方法.

考虑这个例子:

class foo
{
public:
    void const_method() const;
    void nonconst_method();
};

void doit()
{
    const foo f;

    f.const_method();      // this is okay
    f.nonconst_method();   // the compiler will not allow this
}
Run Code Online (Sandbox Code Playgroud)

此外,不允许const方法更改对象的任何成员(除非该成员被特别标记为可变):

class foo
{
public:
    void const_method() const;

private:
    int r;
    mutable int m;
};

void foo::const_method() const
{
    m = 0; // this is okay as m is marked mutable
    r = 0; // the compiler will not allow this
}
Run Code Online (Sandbox Code Playgroud)

  • 可变成员非常有用.编译器仅强制执行按位常量 - 意味着对象的实际位不能更改.但是,如果对象的逻辑状态不受更改的影响,则应将该项声明为可变.例如,如果我有一个查询数据库的对象,那么const对象允许对自己进行选择查询是有意义的.但是在运行函数时可能需要在内部修改一个"database_connection"对象,这可能会在其他查询中重用.在这种情况下,`mutable`可以帮助你维护逻辑const - 一件好事. (3认同)

Dre*_*ann 5

是的,第一个const意味着buffer无法改变.

第二个const暗示这是一个类的成员函数,不会更改对象(this).