c++ passing by const reference

允我心安 提交于 2019-12-19 05:06:28

问题


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

回答1:


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)



回答2:


This is one of best example which shows why data members should not be public.

here, body is constant hence its data members must not be changed, but in body.bp[0]->points point is being changed which is not the member of Body.Hence no const violation.




回答3:


Only body is constant.

body.bp[0]->points is no way affected by the constantness of body




回答4:


Yes, body is constant. That means that no non-const member functions may be called, and no member variables be modified.

Neither is being done. The only member of body used is body.bp[0], which is not changed either, but merely used to get at points, which might or might not be constant...

Corrolary: Don't make data members public.



来源:https://stackoverflow.com/questions/10976702/c-passing-by-const-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!