gpt4 book ai didi

c++ - std::function const 正确性

转载 作者:行者123 更新时间:2023-12-01 22:50:08 25 4
gpt4 key购买 nike

假设我有一个像这样的可调用类型:

struct mutable_callable
{
int my_mutable = 0;
int operator()() { // Not const
return my_mutable++;
}
};

请注意mutable_callable有一个非常量 operator()修改成员变量......

现在假设我创建一个 std::function不符合我的类型:

std::function<int()> foo = mutable_callable{};

现在我可以这样做:

void invoke(std::function<int()> const& z)
{
z();
}

int main()
{
invoke(foo); // foo changed.....oops
}

据我所知std::function operator()const按照: https://en.cppreference.com/w/cpp/utility/functional/function/operator()

所以我的直觉是你不应该这样做......

但是再看看: https://en.cppreference.com/w/cpp/utility/functional/function/function

这似乎对可调用类型是否具有常量 operator() 没有任何限制......

所以我的问题是这样的:我的假设是正确的 std::function<int()> const&本质上与 std::function<int()>& 相同也就是说,两者的行为实际上没有区别……如果是这样的话,为什么不是 const正确吗?

最佳答案

这归结为与 struct A { int* x; }; 相同,其中 const A a;您可以修改 *(a.x) (但不是它指向的地方)。 std::function 中有一个间接级别。 (从类型删除)通过const没有传播。

不,std::function<int()> const& f并非毫无意义。在 std::function<int()>& f您可以将不同的仿函数分配给 f ,您不能在 const 中执行此操作案例。

关于c++ - std::function const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59179293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com