1

当我尝试将一个函数 1 分配给另一个函数 1 时,Boost::function 十次中有一次抛出异常。

Task 是boost::function1<void, void*>.

下面是具体代码:

    // the Task object sent in as Task task
    void Sleeper(void* arg)
    {
        int32_t sleepTime = *(int32_t*)arg;

        SleepCurrentThread((int32_t)sleepTime);
    }

    struct ThreadInfo
    {
        ThreadInfo() : mState(DETACHED), mTask(NULL), mArg(NULL)
        { }

        ThreadState mState;
        Task mTask;
        void* mArg;
    };

    Thread::Thread(Task task, void* arg, IMemoryAllocator& allocator, ILogManager& logger) : mAllocator(allocator), mLogger(logger)
    {
        mThreadInfo = (ThreadInfo*) mAllocator.Allocate(sizeof(ThreadInfo));  // simnple heap allocation

        mThreadInfo->mArg = arg;
        mThreadInfo->mState = Thread::RUNNING;
        mThreadInfo->mTask = task;     //<--------- throws... sometimes


        mHandle = _CreateThread(&Run, (void*)mThreadInfo);
        if (!mHandle)
            Detach();


    }

我专门在 boost function_template.hpp 中将其跟踪到赋值运算符,在这段代码中,它最终抛出:

// Assignment from another BOOST_FUNCTION_FUNCTION
    BOOST_FUNCTION_FUNCTION& operator=(const BOOST_FUNCTION_FUNCTION& f)
    {
      if (&f == this)
        return *this;

      this->clear();
      BOOST_TRY {
        this->assign_to_own(f);        // <--- throws, and then line below re-throws
      } BOOST_CATCH (...) {
        vtable = 0;
        BOOST_RETHROW;
      }
      BOOST_CATCH_END
      return *this;
    }

为什么是这样?我的代码有什么容易发现的问题吗?还有什么需要的吗?

谢谢

编辑:我知道我会被要求使用 boost::threads,但我正在尝试我自己的 win32/pthread 包装器,(为了好玩)

4

1 回答 1

5

struct有一个非平凡的构造函数,但你不调用它。它使Task成员未初始化。要初始化它,要么用 分配整个对象new,要么使用placement new 来初始化它,如下所示:

    void *mem = mAllocator.Allocate(sizeof(ThreadInfo));  // simnple heap allocation
    mThreadInfo = new(mem) ThreadInfo; // placement new

    mThreadInfo->mArg = arg;
    mThreadInfo->mState = Thread::RUNNING;
    mThreadInfo->mTask = task;

Placement new 在已分配的原始(未初始化)内存中构造一个对象。

于 2012-08-31T20:18:01.190 回答