c – 为什么会收到编译错误?
我使用GCC 4.8来编译下面的代码:
#include <memory> template<typename T,typename ...Args> std::unique_ptr<T> make_unique(Args&& ...args) { return std::unique_ptr<T>(new T{std::forward<Args>(args)...}); } struct S { template<class... Args> static std::unique_ptr<S> create(Args&&... args) { return make_unique<S>(std::forward<Args>(args)...); } private: // if I remove this line,then the compilation is OK S(int) {} S() = default; }; int main() { auto s1 = S::create(); // OK auto s2 = S::create(0); // Compilation error } 任何人都可以从编译器中解释这个错误的原因?
解决方法
使用int的构造函数被声明为private,这就是为什么它提供编译错误.请注意,构造函数正在从make_unique(不能访问私有成员)中调用,而不是从创建. 但是,您可能想知道为什么第一次调用create()可以编译好,我认为这是因为GCC有bug.即使在这种情况下也不应该编译,因为默认构造函数也被声明为私有的. Clang正确地给出了两个呼叫的错误(see this). 无论如何,如果你想让他们保持私密,那么让make_unique成为班级的朋友. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |