如何重置一个 std::function?

huangapple go评论61阅读模式
英文:

How to reset an std::function?

问题

std::function 可以为空,并且可以转换为 bool 以测试它是否有目标。但是,如果在分配了内容之后要将其设置为 null,该怎么做呢?

int main()
{
    std::function<void()> f = []() { return 4; };
    f = nullptr; // 重置为空,回到默认构造时的状态。
}
英文:

std::function can be empty, and it's convertible to bool to test if it has a target or not. But, how to set it to null after you've assigned something to it?

int main()
{
	std::function&lt;void()&gt; f = []() { return 4; };
	// how to reset to null, to it&#39;s initial state when default constructed.
}

答案1

得分: 5

你可以选择:

  • nullptr 赋给它:

    f = nullptr;
    
  • 将一个空的 function 赋给它:

    f = std::function<void()>{};
    // 或者:
    f = decltype(f){};
    
  • 与另一个空的 function 进行 swap()

    std::function<void()>{}.swap(f);
    // 或者:
    decltype(f){}.swap(f);
    
英文:

You can either:

  • assign nullptr to it:

    f = nullptr;
    
  • assign an empty function to it:

    f = std::function&lt;void()&gt;{};
    // or:
    f = decltype(f){};
    
  • swap() it with another empty function:

    std::function&lt;void()&gt;{}.swap(f);
    // or:
    decltype(f){}.swap(f);
    

答案2

得分: 5

The simplest way, I use it:

f = {};
英文:

The simplest way, I use it:

f = {};

https://godbolt.org/z/hzEq3xo4e

#include &lt;functional&gt;

int main() {
  std::function&lt;void()&gt; f = []() { return 4; };
  f = {};
}

答案3

得分: 4

nullptr 分配给它以使其为空。

f = nullptr;
英文:

Assign nullptr to it to make it empty.

f = nullptr;

huangapple
  • 本文由 发表于 2023年2月10日 10:18:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定