error :: make_unique不是'std'的成员

Ali*_*786 77 c++ compiler-errors unique-ptr c++11 c++14

我正在尝试编译代码审查上发布的以下线程池程序来测试它.

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>();
Run Code Online (Sandbox Code Playgroud)

Com*_*sMS 126

make_unique即将推出的C++ 14功能,因此即使符合C++ 11标准,您的编译器也可能无法使用它.

但是,您可以轻松地实现自己的实现:

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

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

  • @ ali786取决于您的编译器.例如,使用GCC,您可以在命令行上传递`-std = c ++ 1y`. (6认同)
  • @ ali786实际上,这不是编译器本身的一个特性,而是标准库实现(在您的情况下很可能是[libstdc ++](https://gcc.gnu.org/libstdc++/)).Afaik,仅对gcc 4.9.0添加了对此特定功能的支持([此帖](https://isocpp.org/blog/2014/04/gcc-4.9.0)也建议). (3认同)

Ani*_*753 16

如果您有最新的编译器,则可以在构建设置中更改以下内容:

 C++ Language Dialect    C++14[-std=c++14]
Run Code Online (Sandbox Code Playgroud)

这适合我.


Jag*_* Yu 8

1.gcc 版本 >= 5
2.CXXFLAGS += -std=c++14
3. #include <memory>