This question already has answers here:
Why aren't C++ types const by default?
(3 answers)
Closed 9 years ago.
I read a lot article from website, it said that const help to understand the source better because you have an insurance that the value is fixed. Is this the only reason using const?
By using const you are using the compiler to spot when you are trying to write to something that you shouldn't. I think that having the compiler tell me that I am doing something wrong is always good. Also many compilers will optimise more efficiently when given the information that something in not ever going to change.
It's a good reason, but another is that when you use references wheither they are const or not makes a big difference. For instance
void f(string& ref);
void g(const string& ref);
string h();
f(h()); // illegal code
g(h()); // legal code
The difference is because of the rule you cannot bind a temporary to a non-const reference. The return value of h is a temporary, and so only the call to g is legal. If you have f you would need to use an additional variable
string tmp = h();
f(tmp);
Related
This question already has an answer here:
C++/SDL "initial value of reference to a non-const must be an lvalue"
(1 answer)
Closed 7 months ago.
I want to understand why C++20 complains when I try do the following, perhaps someone can help.
I have a method defined, like so:
void doStuff(Point& dest) {
...
}
When I try to do the following:
doStuff(Point(x,y));
I get the error: C++ initial value of reference to non-const must be an lvalue
This goes away when I make Point& dest -> const Point& dest or if I define a new variable for the Point(x,y) however in the case that I do not want to defined dest as a const or I dont need a variable, why is it that the compiler complains about this? There are cases where I want to pass it in as a reference and others where I want to keep it inline with the function call to keep things more straight forward. Obviously the example I gave here is really simple, but you get the idea.
Of note I know that I can cast it like so:
doStuff(static_cast<Point&>(Point()));
But this seems really unnecessary, I'd like to find a way to achieve this without all the other nonsense. Any help is most appreciated! I might be missing something really obvious, I am no C++ expert.
you can accept (overload with) rvalue references void doStuff(Point&& dest)
side note: you can pass it directly to lvalue reference version if that's what you want.
void doStuff(Point& dest);
inline void doStuff(Point&& dest) { doStuff(dest); }
This question already has answers here:
Literal initialization for const references
(3 answers)
Closed 2 years ago.
My understanding is that a const T& is internally implemented via a const T *const. If so, how is the below code valid (since we cannot take the address of 7)?
const int& i = 7;
Or does the compiler does some trick here? If so, what?
You cannot take the address of a literal like 7 but you can take the address of a temporary object whose value is 7.
Think of that line to be equivalent to
const int unnamed_temprary_variable = 7;
const int& i = unnamed_temprary_variable;
Or does the compiler does some trick here? If so, what?
The compiler does something analogous to the two lines I mentioned but it is not a trick. It is required by the language.
Searching for "extending the lifetime of temporaries" in SO resulted in a long list.
This question already has an answer here:
When to use const references over const value in function?
(1 answer)
Closed 5 years ago.
Is it worth to pass bool by reference ?
void foo(const bool& iflag);
vs
void foo(const bool iflag);
I heard bool reference take much time than bool declaration, but I could not check it.
I'd always pass it by value, unless I wanted to defeat implicit conversions at the calling site, in which case const reference could be a sensible choice.
As for performance reasons though, if you're in any doubt, check the generated assembly. Instinct suggests to me a potential overhead in the case of the reference, although a compiler might optimise out the mess.
Interestingly though the C++ standard does not mandate a size for bool; it could be absolutely enormous in an intentionally hostile compiler. Plus the standard provides no mechanism for inspecting the size of a reference: sizeof(T&) is always sizeof(T).
This question already has answers here:
Use of 'const' for function parameters
(31 answers)
Closed 7 years ago.
I was reading my C++ book (Deitel) when I came across a function to calculate the volume of a cube. The code is the following:
double cube (const double side){
return side * side * side;
}
The explanation for using the "const" qualifier was this one: "The const qualified should be used to enforce the principle of least privilege, telling the compiler that the function does not modify variable side".
My question: isn't the use of "const" redundant/unnecessary here since the variable is being passed by value, so the function can't modify it anyway?
The const qualifier prevents code inside the function from modifying the parameter itself. When a function is larger than trivial size, such an assurance helps you to quickly read and understand a function. If you know that the value of side won't change, then you don't have to worry about keeping track of its value over time as you read. Under some circumstances, this might even help the compiler generate better code.
A non-trivial number of people do this as a matter of course, considering it generally good style.
You can do something like this:
int f(int x)
{
x = 3; //with "const int x" it would be forbidden
// now x doesn't have initial value
// which can be misleading in big functions
}
This question already has answers here:
Two different values at the same memory address
(7 answers)
Closed 5 years ago.
I have the following code:
int main(){
const int a = 1;
const int* b(&a);
int* c = const_cast<int*>(b);
*c = 29;
cout<<*c<<a<<*b;
return EXIT_SUCCESS;
}
Why doesnt the value of 'a' change to 29? Does this mean that the constness of a is not removed when const_casting b?
Constant variables also allows the compiler certain optimizations, one of these is that the compiler can keep the value in the registers and not reload it. This improves performance but will not work with variables that changes since these need to be reread. Some compilers even optimize constants by not allocating a variable, but simply replacing the value inline. If you change the variable a to int instead of const int it will work, as it can be read in the documentation about the const_cast operator from IBM:
If you cast away the constness of an
object that has been explicitly
declared as const, and attempt to
modify it, the results are undefined.
You can find more information about the problem you are having and why it doesn't work here:
The const_cast operator (IBM)
C++ const_cast usage instead of
C-style
casts
const_cast
confusion
On a side note it can be noted that if you find yourself in need of using the const_cast there is a good chance that you should reconsider your design instead.