C++ this 和常量对象

标签 c++ this constants callable-object

你能告诉我为什么这段代码有效吗? replace_if 算法使用了重载的 operator()。在 main 函数中,我创建了 IsEqual 类的常量对象,因此只应使用常量函数成员。不知何故,恒定性不起作用,该运算符被调用。

#include <iostream>
#include <vector>
#include <algorithm>

class IsEqual {
    int value;
public:
    IsEqual(int v) : value(v) {}
    bool operator()(const int &elem){
    this->value=6;
    return elem == value;
    }
};

int main()
{
    const IsEqual tst(2);
    std::vector<int> vec = {3,2,1,4,3,7,8,6};
    std::replace_if(vec.begin(), vec.end(), tst, 5);
    for (int i : vec) std::cout << i << " ";
    std::cout<<std::endl;
}

结果:3 2 1 4 3 7 8 5

最佳答案

std::replace_if 将制作它自己的 tst 对象拷贝。不需要限制为const

如果你想在算法中使用原始对象,你可以使用一个std::reference_wrapper。由于它将引用 const 对象,这将导致编译器错误,因为它要求运算符是 const:

std::replace_if(vec.begin(), vec.end(), std::ref(tst), 5);

关于C++ this 和常量对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31117755/

相关文章:

C++ const 成员函数正在修改成员变量

c++ - 为什么 doxygen 总是重新处理每个文件?

c++ - 如何设置 Clang-Format Style Options 以在捕获之前不换行?

javascript - VueJS + Canvas-Context 如何链接在一起?

javascript - 如何在javascript中的数组内使用 "this"关键字?

c++ - 在 C++ 中,作为类成员的引用应为常量或非常量

c++ - 常量成员和运算符=

c++ - 如何解决 <<ClassName>> 的 "undefined reference to ` vtable 错误?

c++ - 什么是 int(a)(1)?这是一个有效的 c++ 语法吗?

this - .this 或 sap.ui.getCore().byId()