gpt4 book ai didi

c++ - 我应该复制一个 std::function 还是总是可以引用它?

转载 作者:IT老高 更新时间:2023-10-28 13:22:18 34 4
gpt4 key购买 nike

在我的 C++ 应用程序(使用 Visual Studio 2010)中,我需要存储一个 std::function,如下所示:

class MyClass
{
public:
typedef std::function<int(int)> MyFunction;
MyClass (Myfunction &myFunction);
private:
MyFunction m_myFunction; // Should I use this one?
MyFunction &m_myFunction; // Or should I use this one?
};

如你所见,我在构造函数中添加了函数参数作为引用。

但是,在我的类中存储函数的最佳方式是什么?

  • 由于 std::function 只是一个函数指针并且函数的“可执行代码”可以保证保留在内存中,我可以将函数存储为引用吗?
  • 如果传递了 lambda 并且调用者返回,我是否必须制作拷贝?

我的直觉是存储引用(甚至是 const 引用)是安全的。我希望编译器在编译时为 lambda 生成代码,并在应用程序运行时将此可执行代码保存在“虚拟”内存中。因此可执行代码永远不会被“删除”,我可以安全地存储对它的引用。但这真的是真的吗?

最佳答案

Can I store the function as a reference since std::function is just a function-pointer and the 'executable code' of the function is guaranteed to stay in memory?

std::function不仅仅是一个函数指针。它是任意可调用对象的包装器,并管理用于存储该对象的内存。与任何其他类型一样,存储引用是安全的只有在您有其他方法来保证所引用的对象在使用该引用时仍然有效。

除非您有充分的理由存储引用,并且有办法保证它仍然有效,否则按值存储它。

路过const对构造函数的引用是安全的,并且可能比传递值更有效。路过非const引用是个坏主意,因为它会阻止您传递临时值,因此用户无法直接传递 lambda,bind 的结果, 或除 std::function<int(int)> 之外的任何其他可调用对象自己。

关于c++ - 我应该复制一个 std::function 还是总是可以引用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8711391/

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