What are the advantages of const in C++ (and C) for the uninitiated?
问题:
回答1:
Const is particularly useful with pointers or references passed to a function--it's an instantly understandable "API contract" of sorts that the function won't change the passed object.
See also: http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.4
回答2:
When used as a const reference in a function, it lets the caller know that the thing being passed in won't be modified.
void f(Foo &foo, const Bar &bar) { ... }
In this case the caller will know that the foo
might be modified, but the bar
will not. The compiler will enforce this when compiling the body of f()
, so that bar
is never modified and never passed on to another function that might modify it.
All of the above safeguards can be bypassed using const_cast
, which is why such a cast is considered "dangerous" (or at the very least, suspicious).
回答3:
Seems pretty obvious - it keeps you from modifying things that shouldn't be modified.
Edit: for more guidance, always look to Herb Sutter.
回答4:
I'm not so convinced on the "safety" aspect of const (there's pros and cons)....however, what it does allow is certain syntax that you can't do without const
void blah(std::string& x)
{}
can only take a std::string object... However if you declare it const :-
void blah(const std::string& x) {}
you can now do
blah("hello");
which will call the appropriate constructor to make a std::string
回答5:
Also, by using const, you state your intention for the use of a variable or parameter. It is a good programming practice ("C/C++ Coding Style & Standards", item 2.3).
Also by avoiding using #define's to define constants and using const's, you increase the type-safety of your code. C++ Programming Practice Guidelines - item 2.1
回答6:
The contract aspect of const is also important to the compiler's optimizer. With certain const declarations, optimizations involving loop invariants are easier for the optimizer to spot. This is why const_cast is truly dangerous.