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));
}
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.
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.
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.
- 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With