สมมติว่าฉันมีประเภท callable ดังนี้
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::functions operator()เป็นconstตาม:
https://en.cppreference.com/w/cpp/utility/functional/function/operator ()
ดังนั้นความรู้สึกของฉันคือคุณไม่ควรทำสิ่งนี้ .....
แต่จากนั้นดูที่: https://en.cppreference.com/w/cpp/utility/functional/function/function
ดูเหมือนว่านี่จะไม่มีข้อ จำกัด ใด ๆ กับชนิด callable ที่มีค่าคงที่operator()......
ดังนั้นคำถามของฉันคือ: ฉันถูกต้องในการสมมติว่าstd::function<int()> const&เป็นสิ่งเดียวกับstd::function<int()>&ที่ไม่มีความแตกต่างระหว่างพฤติกรรมของทั้งสอง ...... และถ้าเป็นกรณีที่ว่าทำไมมันไม่constถูกต้อง?
std::functionการดำเนินงาน: i.stack.imgur.com/eNenN.pngusing _Ptrt = _Func_base<_Ret, _Types...>ที่ ฉันพักกรณีของฉัน
std::functionมีสิ่งที่เทียบเท่ากับstruct a{ std::any x; };มันอยู่ในนั้น .....