c++ function syntax/prototype - data type after brackets

蓝咒 提交于 2020-05-13 01:23:19

问题


I am very familiar with C/C++ standard function declarations. I've recently seen something like this:

int myfunction(char parameter) const

The above is only a hypothetical example and I don't even know if it makes sense. I'm referring to the part AFTER the parameter. The const. What is this?

A more real example:

wxGridCellCoordsArray GetSelectedCells() const

This can be found here So what exactly is that text const doing at the end of the line?


回答1:


The const keyword, when shown after a function, guarantees the function caller that no member data variables will be altered. It also changes the function signature, which is something less known to some C++ programmers. You can actually overload a function in C++ by adding the const keyword after a function with the same name. For example:

void changeValue() const;
void changeValue();

Both of the above functions are valid and an overload of each other. I often see some C++ API's and frameworks use this overload to avoid a plethora of compile errors when users call these functions within const and non-const functions. Whether this is good C++ software engineering is up for debate. I would imagine it is bad practice, but it is good to be aware that it changes the function signature.

For instance given this class,

// In header
class Node {

public:

Node();

void changeValue() const;

~Node();

private:

int value;

};

// in .cpp

void Node::changeValue() const {
    this->value = 3; // This will error out because it is modifying member variables
}

There is an exception to this rule. If you declare that a member data variable is mutable, then it can be altered regardless if the function is declared to be const. Using mutable is for the rare situation where an object is declared constant, but in practice has member data variables which need the option to change. One potential example of its use is caching a value that you may not want to repeat the original calculation. This is typically rare... But it is good to be aware of it. A good reference of software engineering decisions around Mutable is the concept of bitwise const vs conceptual const. With bitwise const, the programmer is informing the reader that when const is present, no bits for that const object shall change without a const_cast. With conceptual const, the idea is that the user of the class should not care whether the bits of the mutable variable should change as it does not impact the usage of the class from the user's perception. Here is a good article explaining the difference and the ups and downs of using Mutable - https://www.cprogramming.com/tutorial/const_correctness.html

For instance given this class,

// In header
class Node {

public:

Node();

void changeValue() const;

~Node();

private:

mutable int value;

};

// in .cpp

void Node::changeValue() const {
    this->value = 3; // This will not error out because value is mutable
}



回答2:


The const says that the function will not change any of the data members of this unless they are marked mutable.
Only a member function can be marked const so this means that none of the members will be changed inside the function.




回答3:


It's a "defensive programming" technique to help guard against your own programming errors. With const against a function parameter, you are stating that the function should not modify that parameter, and adding the const causes the compiler to prevent you from inadvertently doing so. Similarly, if you write a member function which shouldn't change any member variables of your class, then you can declare the whole function const like that, and it will prevent you from doing so.

It also helps to make your code self-documenting. Adding const to a parameter tells a user that 'this function does not modify this parameter'. Adding const to a member function tells the user that 'this function does not modify any members of the class' (except explicitly mutable ones).

Restricting access to something except for those occasions where you really need it should generally be considered to be a good thing. It's the exact same reason why you don't routinely log onto your own system as root, even though you could, and you'd have more power if you did.




回答4:


The const keyword after a method means that the implicit this parameter (which is set to the address of the object used to invoke the method) points to a constant object.

In C++. a member function could look like:

class Foo {
    int x;
    mutable int y;
public:
    void bar ()       {
        Foo *me = this;          // * this is an implicit parameter
                                 //   that points to the instance used
                                 //   to call bar()
        assert(&x == &this->x);  // * accesses to class members are
                                 //   implicitly taken from this
        x = 1;                   // * can modify data members
    }
    void bar () const {
        // Foo *me = this;       // * error, since "bar() const" means
                                 //   this is a "const Foo *"
        const Foo *me = this;    // * ok
        // x = 1;                // * error, cannot modify non-mutable
                                 //   members of a "const Foo"
        y = 0;                   // * ok, since y is mutable
    }
};

The analog in C would be functions to access a struct Foo * and a const struct Foo *, respectively:

struct Foo {
    int x;
    int y;
};

void Foo_bar (Foo *this)        { /* ... */ } /* can modify this->x and this->y */
void cFoo_bar (const Foo *this) { /* ... */ } /* cannot modify this->x nor this->y */

There is no mutable analog in C.



来源:https://stackoverflow.com/questions/17824057/c-function-syntax-prototype-data-type-after-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!