[英]std::function const correctness
Suppose I have a callable type like so:假设我有一个像这样的可调用类型:
struct mutable_callable
{
int my_mutable = 0;
int operator()() { // Not const
return my_mutable++;
}
};
Note that mutable_callable
has a non-const operator()
that modifies a member variable.....请注意,
mutable_callable
具有修改成员变量的非常量operator()
.....
Now suppose I create a std::function
out of my type:现在假设我根据我的类型创建了一个
std::function
:
std::function<int()> foo = mutable_callable{};
Now I can do this:现在我可以这样做:
void invoke(std::function<int()> const& z)
{
z();
}
int main()
{
invoke(foo); // foo changed.....oops
}
Now as far as I can tell std::function
s operator()
is const
as per: https://en.cppreference.com/w/cpp/utility/functional/function/operator()现在,据我所知
std::function
s operator()
是const
: https://en.cppreference.com/w/cpp/utility/functional/function/operator()
So my gut feeling is that you shouldn't be able to do this.....所以我的直觉是你不应该这样做......
But then looking at: https://en.cppreference.com/w/cpp/utility/functional/function/function但随后查看: https : //en.cppreference.com/w/cpp/utility/functional/function/function
This doesn't seem to put any constraints on whether or not the callable type has a constant operator()
......这似乎对可调用类型是否具有常量
operator()
没有任何限制......
So my question is this: I am correct in assuming that std::function<int()> const&
is essentially the same thing as std::function<int()>&
that is there is no actually difference between the behavior of the two......and if that is the case why is it not const
correct?所以我的问题是这样的:我是正确的假设
std::function<int()> const&
本质上是一样的东西std::function<int()>&
这是没有实际的行为之间的区别二......如果是这种情况,为什么它不是const
正确的?
This boils down to the same as struct A { int* x; };
这归结为与
struct A { int* x; };
相同struct A { int* x; };
struct A { int* x; };
, where in a const A a;
, 其中在一个
const A a;
you can modify the value of *(ax)
(but not where it points to).您可以修改
*(ax)
的值(但不能修改它指向的位置)。 There is a level of indirection in std::function
(from the type erasure) through which const
is not propagated. std::function
有一个间接级别(来自类型擦除), const
不会通过它传播。
And no, std::function<int()> const& f
is not pointless.不,
std::function<int()> const& f
并非毫无意义。 In a std::function<int()>& f
you would be able to assign a different functor to f
, which you cannot do in the const
case.在
std::function<int()>& f
您可以将不同的函子分配给f
,而在const
情况下则不能这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.