C++ passing const bool by reference [duplicate] - c++

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).

Related

Why use const proactively? C++ [duplicate]

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);

Should I declare a parameter that will never be changed as a const variable? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use of 'const' for function parameters
For example,
void Func(int para);
If I know I don't want to change para's value in Func(...), should I instead declare para as "const int" to guarantee that? i.e.
void Func(const int para);
BTW, I think
void Func(const int &para);
is not an appropriate alternative sometimes because const int& is usually implemented by underlying pointer, thus it is essentially equivalent to
void Func(const int *p_para);
The book "C++ Coding Standards: 101 Rules" p31 says that "void Func(const int para);" is bad as it will "confuse" the readers of the header files. I'm not sure though...
After thought it over, I think a good solution is to declare it as "void Func(int para);" and use "void Func(const int para) {...}" when implement it. I find that the word "const" in "void Func(const int para);" will be silently dropped by the compiler...
If you do this at all (and some people do) then you should put the const in the definition (where it is useful) but not the declaration (where it is noise, it doesn't affect the caller).
So:
void F(int param);
...
void F(int const param) {
...
}
Declaring an argument as const serves three purposes:
It tells the compiler that the value is constant, which may enable certain optimizations. Given today's "smart" compilers, I'm not sure that it's still relevant.
It tells programmers at a glance that the value does not change within the function, which may be helpful as they debug/enhance the code.
It makes the compiler actually enforce your assertion that the function does not change the value.
In general it's a good idea to declare variables as const if you can, for the same reason it's a good idea to eliminate compiler warnings: it makes your code easier to support.
I think it will only serve to clarify things for readers of header files, by marking a parameter const it is effectively saying it is input only. Likewise the & reference operator is read as the parameter being modified in the function with effect on the passed parameter. This may be where the confusion arises, however const int &para is const "before" it is & reference and doesn't require much interpretation.
I confuse & and * notation because I am used to C where the & operator does not exist. But for C++, I would recommend you use it.
const int para: useful to you as it stops you modifying para by mistake. Not sure about the confusion issue.
const int &para: You should do this, indeed sometimes you have to if code elsewhere insists that you keep para constant (for example if you are writing a custom comparator function for a map). It's also more efficient than const int para - if you are not modifying para why do you need to copy it?
I don't think it matters what const int &para is implemented as underneath. What matters is that on top you can't modify it (without being evil) so the effect is the same as const int para but more efficient.
You should not. in C, parameters are been passed by value, so the caller don't need to know what do you do with the int it pass. even if your function is void func(int), you can pass a const int to it.
void func(int a) {
a=5;
}
...
const int b=7;
func(b);
In this code, b will still be 7, since the function only changed the local variable a.
Of course, if the function get a pointer, or a reference, it's different. if the declaration is void func(int &a), then the above code is illegal, since func changed b, which is const, and therefor if your function doesn't change the reference, and you want the possibility to pass a const int to it, you should declare the parameter as const.

Isn't "const" redundant when passing by value? [duplicate]

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
}

When to use const and const reference in function args?

When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be changed or a const pointer if the pointer won't be changed.
When else is this practice advised?
When would you use a const reference and what are the advantages over just passing it through a pointer for example?
What about this void MyObject::Somefunc(const std::string& mystring) What would be the point in having a const string if a string is in fact already an immutable object?
Asking whether to add const is the wrong question, unfortunately.
Compare non-const ref to passing a non-const pointer
void modifies(T &param);
void modifies(T *param);
This case is mostly about style: do you want the call to look like call(obj) or call(&obj)? However, there are two points where the difference matters. If you want to be able to pass null, you must use a pointer. And if you're overloading operators, you cannot use a pointer instead.
Compare const ref to by value
void doesnt_modify(T const &param);
void doesnt_modify(T param);
This is the interesting case. The rule of thumb is "cheap to copy" types are passed by value — these are generally small types (but not always) — while others are passed by const ref. However, if you need to make a copy within your function regardless, you should pass by value. (Yes, this exposes a bit of implementation detail. C'est le C++.)
Compare const pointer to non-modifying plus overload
void optional(T const *param=0);
// vs
void optional();
void optional(T const &param); // or optional(T param)
This is related to the non-modifying case above, except passing the parameter is optional. There's the least difference here between all three situations, so choose whichever makes your life easiest. Of course, the default value for the non-const pointer is up to you.
Const by value is an implementation detail
void f(T);
void f(T const);
These declarations are actually the exact same function! When passing by value, const is purely an implementation detail. Try it out:
void f(int);
void f(int const) {/*implements above function, not an overload*/}
typedef void C(int const);
typedef void NC(int);
NC *nc = &f; // nc is a function pointer
C *c = nc; // C and NC are identical types
The general rule is, use const whenever possible, and only omit it if necessary. const may enable the compiler to optimize and helps your peers understand how your code is intended to be used (and the compiler will catch possible misuse).
As for your example, strings are not immutable in C++. If you hand a non-const reference to a string to a function, the function may modify it. C++ does not have the concept of immutability built into the language, you can only emulate it using encapsulation and const (which will never be bullet-proof though).
After thinking #Eamons comment and reading some stuff, I agree that optimization is not the main reason for using const. The main reason is to have correct code.
The questions are based on some incorrect assumptions, so not really meaningful.
std::string does not model immutable string values. It models mutable values.
There is no such thing as a "const reference". There are references to const objects. The distinction is subtle but important.
Top-level const for a function argument is only meaningful for a function implementation, not for a pure declaration (where it's disregarded by the compiler). It doesn't tell the caller anything. It's only a restriction on the implementation. E.g. int const is pretty much meaningless as argument type in a pure declaration of a function. However, the const in std::string const& is not top level.
Passing by reference to const avoids inefficient copying of data. In general, for an argument passing data into a function, you pass small items (such as an int) by value, and potentially larger items by reference to const. In the machine code the reference to const may be optimized away or it may be implemented as a pointer. E.g., in 32-bit Windows an int is 4 bytes and a pointer is 4 bytes. So argument type int const& would not reduce data copying but could, with a simple-minded compiler, introduce an extra indirection, which means a slight inefficiency -- hence the small/large distinction.
Cheers & hth.,
The main advantage of const reference over const pointer is following: its clear that the parameter is required and cannot be NULL.
Vice versa, if i see a const pointer, i immedeately assume the reason for it not being a reference is that the parameter could be NULL.

Should I return bool or const bool?

Which is better:
bool MyClass::someQuery() const;
const bool MyClass::someQuery() const;
I've been using 'const bool' since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and Intellisense not helping out any ;) Can anyone confirm that?
To me returning const values (this isn't just about bools) makes more sense; it'll prevent temporaries being modified, which is almost always going to be a programmer mistake. I just want something to back that up so I can extol returning const values to my colleagues :)
This is the case when const adds no value but inflates the code and makes the reader think more. What's the point of this const? The caller can copy the value into some non-const variable and do whatever he wants with it anyway.
So you know it's right, you're just after the Voice of Authority?
Preventing accidental modification of temporaries is very valuable. In general, you should declare as many things as you possibly can const, it protects you from a variety of accidents and gives the optimiser useful hints.
D'you have a copy of Scott Meyers' "Effective C++" around? Point them at Item 3 (page 18 in the third edition) ;)
It gives the example of
class Rational {...};
const Rational operator* (const Rational& lhs, const Rational& rhs );
if( (a * b) = c ) // declaring operator *'s return value const causes error to be caught by compiler
Note that if((a*b) = c) won't compile for built-in types anyway, so it is very relevant here whether we're talking built-in types (your question asks for bool) or user-defined types.
For built-in types it makes no sense at all, so it shouldn't be used. And for user-defined types, I'm in jalf's camp: What if the caller wants to modify the returned object?
I'm not convinced that if((a*b) = c) is such a good argument for returning const user-defined types, since I can't remember the last time I've seen a compiler not warn about this.
To be a little more specific, only "objects" can be const. The C++ standard's definition of "object" includes everything an lvalue refers to ("has a name") and class-type temporaries. A boolean return value is an rvalue of a non-class type which is why a standards-compliant compiler will just ignore "const" in this case. As others said already, it's useless in this context.
When you returning a refernce to a member variable it makes sense to make it const. Here you are returning a copy, hence there is no need of const.
The const modifier is only used for return types that are returned by reference (either as reference const SomeObject& or via a pointer const SomeObject*), so the caller won't be able to modify the object via the reference/pointer. Primitive types are returned by value, which means that the caller receives a copy of the the object, not the object itself.
Therefore, const is not really appropriate for returned value types. Since the copy is outside of the control of the called function, the called function should not dictate to the caller that it cannot be changed.
This is an ancient post, but I think it's worth mentioning there is a potential corner case here since C++11. While, as stated by others, it will make no difference whether you use const bool or bool as return type in most cases, if you are using C++11 decltype and associates, e.g. result_of, you could declare a variable with the same type as the returning value of some function, and so the const would actually have an effect in this case.
It completely doesn't matter. Therefore, the consensus is to return just bool.
The reason that it doesn't matter is that you can't call non-const member functions anyway; bool is not a class or struct.
As bool is going to be copied, it's the same, to put const or not. Plus you'll may have some compil problems.
const return type
SUMMARY:
The value of a return type that is
declared const cannot be changed. This
is especially usefull when giving a
reference to a class’s internals, but
can also prevent rarer errors.
const bool func();
bool f = func();
0 errors, 0 warnings. What have you accomplished other than unnecessary code inflation?