Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ passing by const reference

Tags:

In the following program body cosists of a vector of pointers. Points is a struct of x,y,z coordinates and a point_id. I believe as body is passed by const reference, the following step should produce an error. BUt the program is running without any problem. Can you please explain me why is this.

void readOutFile(const Body& body, int n){

    ....

    body.bp[0]->points.push_back(Point_id(p,i));
}
like image 369
user829209 Avatar asked Jun 11 '12 08:06

user829209


People also ask

What is pass by const reference?

Passing By Reference To Const in C++ Passing By Reference To Const in C++ C++ is an example of a message-passing paradigm language, which means that objects and values are passed to functions, which then return further objects and values based on the input data.

Should I always pass const reference?

It's wrong. Passing the arguments of basic types (int, float, char....) is more effecient than passing them by reference. const & is more effecient in passing the BIG OBJECT. Because the reference is a alias of a object in essential, the compiler need to handle more information.

What is the difference between pass-by-reference and pass by const reference?

From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified.

What is a const reference C++?

- const references allow you to specify that the data referred to won't be changed. A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const.


1 Answers

Here's the issue:

body.bp[0]->points.push_back(Point_id(p,i));
          ^^

Indirecting through a pointer removes any constness; rather, the constness of the result is dependent on the type of the pointer.

T *t;              // pointer to T: can modify t and (*t)
const T *t;        // pointer to const-T: can modify t but not (*t)
T *const t;        // const-pointer to T: can modify (*t) but not t
const T *const t;  // const-pointer to const-T: can't modify either t or (*t)
like image 113
ecatmur Avatar answered Nov 12 '22 17:11

ecatmur