error::make_unique 不是‘std’的成员

2021-12-31 00:00:00 compiler-errors c++ c++11 unique-ptr c++14

我正在尝试编译发布在代码审查上的以下线程池程序以对其进行测试.

I am trying to compile the following thread pool program posted on code review to test it.

https://codereview.stackexchange.com/questions/55100/platform-independant-thread-pool-v4

但我收到错误

threadpool.hpp: In member function ‘std::future<decltype (task((forward<Args>)(args)...))> threadpool::enqueue_task(Func&&, Args&& ...)’:
threadpool.hpp:94:28: error: ‘make_unique’ was not declared in this scope
     auto package_ptr = make_unique<task_package_impl<R, decltype(bound_task)>>  (std::move(bound_task), std::move(promise));
                        ^
threadpool.hpp:94:81: error: expected primary-expression before ‘>’ token
     auto package_ptr = make_unique<task_package_impl<R, decltype(bound_task)>>(std::move(bound_task), std::move(promise));
                                                                             ^
main.cpp: In function ‘int main()’:
main.cpp:9:17: error: ‘make_unique’ is not a member of ‘std’
 auto ptr1 = std::make_unique<unsigned>();
             ^
main.cpp:9:34: error: expected primary-expression before ‘unsigned’
 auto ptr1 = std::make_unique<unsigned>();
                              ^
main.cpp:14:17: error: ‘make_unique’ is not a member of ‘std’
 auto ptr2 = std::make_unique<unsigned>();
             ^
main.cpp:14:34: error: expected primary-expression before ‘unsigned’
 auto ptr2 = std::make_unique<unsigned>();

推荐答案

make_unique 是一个 即将推出的 C++14 功能,因此可能无法在您的编译器上使用,即使它符合 C++11.

make_unique is an upcoming C++14 feature and thus might not be available on your compiler, even if it is C++11 compliant.

然而,您可以轻松推出自己的实现:

You can however easily roll your own implementation:

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

(仅供参考,这里是最终版本make_unique 被投到 C++14 中.这包括覆盖数组的附加功能,但总体思路仍然相同.)

(FYI, here is the final version of make_unique that was voted into C++14. This includes additional functions to cover arrays, but the general idea is still the same.)

相关文章