簡體   English   中英

std::function const 正確性

[英]std::function const correctness

假設我有一個像這樣的可調用類型:

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 s operator()consthttps://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; };相同struct A { int* x; }; struct A { int* x; }; , 其中在一個const A a; 您可以修改*(ax)的值(但不能修改它指向的位置)。 std::function有一個間接級別(來自類型擦除), const不會通過它傳播。

不, std::function<int()> const& f並非毫無意義。 std::function<int()>& f您可以將不同的函子分配給f ,而在const情況下則不能這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM