according to some tutorials i read a while back, the "const" declaration makes a variable "constant" ie it cannot change later.
But i find this const declaration abit inconveniencing since the compiler sometimes gives errors like"cannot convert const int to int"
or something like that.
and i find myself cheating by removing it anyway.
question: assuming that i am careful 开发者_开发技巧about not changing a variable in my source code, can i happily forget about this const stuff?
Thanks in advance
Are you serious? Why would you want to give up on such a useful feature just because you make a mistake sometimes? Better try and learn to avoid mistakes with const
and you benefit from the great assistance it adds to ensure correctnes with your code.
Of course, you can say goodbye to all the help the language provides, and tell the compiler thereby not tell you about mistakes in your code anymore. Instead, you will have to ask the debugger later on where your bugs are. Not sure whether that's better.
In C++, "const" can a apply to a variable (making it unchangeable) or a function (rendering it unable to change other things).
My use of "const" is not just to prevent my code from changing my variable. It's to prevent some idiot's code from changing my variable (especially if the idiot is me six months from now) and to prevent my code from changing a critical variable some idiot left exposed (especially if the idiot was me six months ago).
If you are careful, yes. But it is human to err. Also, you do not give the compiler the opportunity to optimize around these constants.
The error message that you get is because you try to alter a const int
. Simply assigning the value to a (non-const) int
, you alter it as you want to.
Const helps you, try to sprinkle more of it around and listen to the compiler. That will help you produce better code.
Even if you and everyone you work with never makes mistakes, the use of const in your method declarations helps to document your interface.
You lose some useful language features without const, especially regarding references. Consider:
void f(const MyClass& m);
void f(const int& i);
// ...
f(MyClass()); // OK, can pass temporary as const reference
f(5); // OK as well, 5 is a temporary int
If you consider the 'const' optional and get rid of it:
void f(MyClass& m);
void f(int& i);
// ...
f(MyClass()); // Error, cannot pass temporary as non-const reference
f(5); // Error, same as above
The idea behind using 'const' is specifically that you ensure compiler errors when attempting to alter a variable's value when it has been predetermined (by using const
) that you do NOT want to do so. It's essentially built in error-checking, and is useful for many reasons.
This is especially valuable in cases such as an external interface and public methods as a way of guaranteeing the caller that a passed value will not be modified.
const
also locks in the intent to not modify, and prevents accidental assignment.
While making const
use mandatory is unnecessary, it is very useful and good practice.
Here's a useful explanation you may want to check out: http://duramecho.com/ComputerInformation/WhyHowCppConst.html
You can forget about it but isn't it nice if the compiler forces it upon you? That way, your "const" variables actually stay constant.
Its always optional. If its all your code sure you can forget it ( I wouldn't recommend it, because it protects you), but when you interact with others, you're essentially providing a contract for them that you won't change their object or calling a function does not change the state of your object. This can be invaluable when you are not familiar with other's code, or you don't have the source.
To answer your question first:
Yes, you can. But only if you are careful, and everyone else who uses your code from now to eternity is also careful.
So, on balance you are better off thinking about why you should make something const
and when you should not.
Another technique for exploring why const makes a difference is to try to make everything const at first until you have valid reasons to change something, then, and only then, remove the minimum number of consts until it works again.
Glad to see you are thinking about the issue - its more than most do.
People usually face this problem when they start using the const keyword. Believe me, it really helps. Leave it to the compiler to take care of the cosntness of the variable, instead of you taking care to not alter its value anywhere.
Changing things that shouldn't be changed is one of the most common sources of error. It is therefore worthwhile specifying const because it prevents you from doing something wrong. Why would you want to give that up?
const double PI = 3.14159265358979;
PI=4; // generates a compiler error (good)
There are some problems with the c++ notation, because a constant can only be initialized, not assigned the first time, and sometimes, you don't have the value at initialization time.
class A {
private:
const int num;
public:
A(int x, int y) : num(0) { // oops, I don't yet know what num should be
while ( ... ) {
}
num = ...;
}
};
The way out of this one is to define a private function that computes the value of num but sometimes that means that instead of one clean block of code in the constructor, you are forced to split it into sections in awkward ways, just so you can initialize the variable.
class A {
private:
const int num;
int computeNum(int x, int y) { ... }
public:
A(int x, int y) : num(f(x,y)) {
}
};
Sometimes, you have a value that is generally supposed to be const, but you want to selectively override that when it semantically makes sense. For example, social security numbers don't change, unless your identity is stolen. So you have just one method, called createNewSSN() which changes the otherwise constant ssn
class Person {
private:
const int ssn;
public:
Person(int ssn_) : ssn(ssn_) {}
void createNewSSN(int newssn) {
log << "Changed SSN: " << ssn << " to " << newssn << "\n";
*(int*)&ssn = newssn; // trust me, this is a special case....
}
};
精彩评论