I've been looking all over to try and figure out when const
should be used and what it does. I thought I had a decent grasp but it looks like the C++11 standard has changed some things.
Are the below true?
True for all versions of c++
const int integer = 3;
- integer can not be changed
const someObject();
- someObject can not be changed (except for mutable things)
void someMethod() const
- someMethod is not allowed to change any members of it's object. (If both void someMethod()
and void someMethod() const
exist, non-const objects will call void someMethod()
and const objects will call void someMethod() const
.
const int getMyInteger()
- returns an int that can't be changed (c++11 essentially makes obsolete with rvalues)
void doSomething(const int& integer)
- integer's const reference (integer is readonly) is passed rather than passed by value. (preferred over pass by value before c++11)
void pointerMethod(const ptr* pointer)
- not preferred for C++ since references can be used and were designed to be safer. (Basically the same as pass by const reference above minus dereferencing and pointer algebra.)
Prior to C++11
void doSomething(const int integer)
- basically meaningless since a copy is formed anyway. Essentially serves as self-documentation that the copy is not changed in the function/method.
Since C++11
void doSomething(const int integer)
- preferred way to pass parameters since move semantics will move rvalue with guarantee that the object being moved will not be changed. Use whenever possible.
void notCopying(const SomeHugeObject hugeObject)
- as long as SomeHugeObject doesn't have a destructor, copy constructor or copy assignment operator the default move constructor will be called. Otherwise SomeHugeObject will need to define a move constructor and move assignment operator.
I believe these should be all the possible instances where const can be used. (Obviously they can be used in combination as well.)
Mainly are the things I've written under the since c++11 accurate? Are there any other times when const should be used or when c++11 has changed the meaning of something due to the move semantics?
Aucun commentaire:
Enregistrer un commentaire