简体   繁体   中英

Is there a way to declare that input parameter of the function must be const reference?

motivation for this is that (rarely)I have a need to know that the input parameter of the class constructor or function in general is const. Usually when the class is a helper that "automates" some procedure.
Example:
Is this the OK scoped way to get random element from the container?
If you look at the code it is clear that if the container passed to constructor is changed later class functionality is broken. So is there a way to have a function "demand" const instead of "promise" const.

Example:

int f(const vector<int>& v)
{
    return v.size();
}
int main()
{
    vector<int> v;
    v.push_back(42); // can f be changed to reject v because it is not const 
    cout << f(v);

}

Declare but do not implement a non-const version.

int f(vector<int>& v);

Attempts to pass a non-const vector will be resolved to this function, and then you will get a linker error because no such function exists.

Some fancy template games may be able to turn it into a compile-time error.

There is no way to guarantee that. If you want to be sure the object doesn't change, it should be owned by the class. One way to accomplish that is to copy the object you want to keep constant into the class, or if using C++11 to let the constructor take an rvalue-reference, and move the object.

If you want some attributes inside class be safe from any external changes they should be copied by constructor to attribute const TypeName _attr; .

I don't think, it is possible.

If it would be possible, you could still do like that

Object mutable_;
const Object & notMutavle = mutable_;
func(notMutable);
mutable.change();

Anyway, even const object's state can be possibly changed, if it has some mutable feilds.

If you want to be sure, that nobody changes your object, you should manage it yourself.

You can do it by overloading the function for non-const reference.

Next example demonstrates this. However, instead of returning -1, the first version of f should throw an exception.

#include <vector>
#include <iostream>

int f(std::vector<int>& )
{
    return -1;
}
int f(const std::vector<int>& v)
{
    return v.size();
}
int main()
{
    std::vector<int> v;
    v.push_back(42); // can f be changed to reject v because it is not const
    std::cout << f(v)<<std::endl;

    const std::vector<int> cv(5);
    std::cout << f(cv)<<std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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