Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const reference is bad C++ 11

I was watching Bjarne Stroustrup on YouTube and I was trying to figure out why this is considered bad as he said it is C++98 style bad code

void setInt(const unsigned int &i)
void takeaString(const std::string &str)

I mean you are passing a reference to a constant so you save yourself the copy operation and it isnt even using like passing the pointer so it doesnt have to dereference so why is it bad?

like image 409
user3380862 Avatar asked Mar 09 '14 19:03

user3380862


People also ask

Should I always pass const reference?

Always passing a reference and putting const in front of it is tedious and prone to errors. Also, always passing references would mean creating a local variable for each function argument (instead of passing expressions).

Is const reference thread safe?

I recommend to always to use `const` reference since it makes sure shared variables are thread safe provided you don't want to modify the variable during the execution of the thread.

Can references be const?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Does const reference extend lifetime?

In the by-reference case, we get a const Base& reference that refers to a Derived object. The entire temporary object, of type Derived , is lifetime-extended.


1 Answers

In pre-C++11, the general rule of thumb is if you don't modify the argument, pass a built-in type by value and an object of a class or struct by const&, because objects of classes or structs are typically so big that passing by const& pays in terms of performance.

Now that's a fairly arbitrary rule, and you'll also see exceptions, of course (e.g. iterators in the standard library) but it works well in practice and is an established idiom. When you see f(int const &i) or f(std::string s) in some other programmer's code, then you will want to know the reason, and if there's no apparent reason, people will be confused.

In C++11, the story may be different. A lot of people claim that due to new language features (move semantics and rvalue references), passing big objects by value is not a performance problem anymore and may even be faster. Look at this article: "Want Speed? Pass by Value." However, when you look at past Stack Overflow discussions, you will also find that there are experienced programmers opposed to this view.

Personally, I've not made up my mind on this. I consider C++11 too new for me to really judge what's good and bad.

Nevertheless, C++11 is often irrelevant if you have to use a pre-C++11 compiler for whatever reason, so it's important to know the pre-C++11 rules in any case.

like image 165
Christian Hackl Avatar answered Sep 19 '22 00:09

Christian Hackl