简体   繁体   English

C ++ const类参考?

[英]c++ const Class reference?

I have searched google in a long run, but don't get anything related to my question. 我已经长期搜索过google,但没有得到与我的问题相关的任何信息。 Here is the details. 这是详细信息。

Q: 问:

void myfunc(const myclass& para_ins);
int main(){...
    myclass ins;
    myfunc(ins);
...}

If I pass in a function with a class ins like above, what does const parameter actually do to the ins here? 如果我传入一个带有上述类ins的函数,那么const参数实际上对这里的ins有什么作用? Since it is using reference here, I don't think it will make a copy of ins and make every members in it unchangeable, so does it actually change the original class to const? 由于它在这里使用引用,因此我认为它不会复制ins并使其中的每个成员都不可更改,因此它实际上会将原始类更改为const吗? If so, what if there is a multi-thread program that more than 2 thread manipulate the ins at the same time? 如果是这样,如果有一个多线程程序同时由两个以上的线程操作ins,该怎么办? If not, what actually happens here? 如果没有,这里实际发生了什么?

If I pass in a function with a class ins like above, what does const parameter actually do to the ins here? 如果我传入一个带有上述类ins的函数,那么const参数实际上对这里的ins有什么作用?

When a function declares a parameter to be const& , it promises that it will not change the object nor will it call any non- const member function of the object. 当一个函数声明一个参数为const& ,它承诺不会更改该对象,也不会调用该对象的任何非const成员函数。

Since it is using reference here, I don't think it will make a copy of ins and make every members in it unchangeable 由于它在这里使用引用,所以我认为它不会复制ins并使其中的每个成员保持不变

That is correct. 那是对的。

so does it actually change the original class to const? 那么它实际上将原始类更改为const吗?

No, it does not. 不,不是的。 The original object can still be modified in the calling function if it is not a const object in the calling function. 如果原始对象不是调用函数中的const对象,则仍可以在调用函数中对其进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM