c++ - std::function 在移动后是否重置其内部功能

标签 c++ c++11

#include <iostream>
using namespace std;

#include <functional>

        template <class F>
        class ScopeExitFunction
        {
        public:
            ScopeExitFunction(F& func) throw() :
                m_func(func)
            {
            }

            ScopeExitFunction(F&& func) throw() :
                m_func(std::move<F>(func))
            {
            }

            ScopeExitFunction(ScopeExitFunction&& other) throw() :
                m_func(std::move(other.m_func))
            {
             //  other.m_func = []{};
            }

            ~ScopeExitFunction() throw()
            {
                m_func();
            }

        private:
            F m_func;
        };

int main() {
    {
        std::function<void()> lambda = [] { cout << "called" << endl; };
        ScopeExitFunction<decltype(lambda)> f(lambda);
        ScopeExitFunction<decltype(lambda)> f2(std::move(f));
    }
    return 0;
}

不取消注释这一行 //other.m_func = []{}; 该程序产生此输出:

Executing the program.... $demo called terminate called after throwing an instance of 'std::bad_function_call' what(): bad_function_call

std::function 在移动时不重置他的内部函数是否正常?

最佳答案

根据 C++11 20.8.11.2.1/6 [func.wrap.func.con],从现有的 std::function 对象移动构造将原始对象“留在具有未指定值的有效状态”。所以基本上不要假设任何事情。只是不要使用原始函数对象,或者如果您仍然需要它,也不要从它移动。

关于c++ - std::function 在移动后是否重置其内部功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19998389/

相关文章:

c++ - 如何在访问时验证 C++ 对象的状态而不重复

c++ - OCTREE.exe : 0xC0000005: Access violation writing location 0x000000a8 中 0x1000bbae 处未处理的异常

c++ - 是否有像 "cvHoughCircles()"这样的 opencv 函数用于方形检测?

c++ - 非构造函数上的函数 try block 有什么缺点吗?

c++ - 在 C++ 中如何直接初始化对象?

c++ - Objective-C block 字面量语法原理

c++ - 启动 std::thread 时无法将(函数指针)左值绑定(bind)到(函数指针)右值?

c++ - STL iota 包含文件更改

c++ - rethrow_exception 真的可以抛出相同的异常对象,而不是一个拷贝吗?

包含其他对象的类的 C++ 隐式复制构造函数