c++ const 类引用?

标签 c++ class reference constants

我在谷歌上搜索了很长时间,但没有得到与我的问题相关的任何信息。这是详细信息。

问:

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

如果我像上面那样传入一个带有类 ins 的函数,const 参数实际上对这里的 ins 做了什么?既然这里用的是reference,我不认为它会复制ins,让里面的每一个成员都不可改变,那么它真的把原来的class改成const了吗?如果是这样,如果有超过2个线程同时操作ins的多线程程序怎么办?如果不是,这里究竟发生了什么?

最佳答案

If I pass in a function with a class ins like above, what does const parameter actually do to the ins here?

当一个函数声明一个参数为const&时,它 promise 它不会改变对象,也不会调用对象的任何非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

没错。

so does it actually change the original class to const?

不,它没有。如果原始对象在调用函数中不是 const 对象,仍然可以在调用函数中对其进行修改。

关于c++ const 类引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33194565/

相关文章:

C++: friend 模板类/模板非类型参数

c++ - 类型未声明错误

c++ - 检测对已释放的未命名临时文件的访问

c++ - 奇怪的编译器行为

c++ - 为什么 std::cout 以相同的小数精度打印 float 、 double 和长 double ?

c++ - MSB6006 : “CL.exe” exited with code 2 when using openMP

rust - 如何在不使用时有条件地提供默认引用而不执行不必要的计算?

c++ - 改变整个屏幕像素的颜色

c++ - 指针数组和类型转换

c++ - 关于引用指针的说明