为什么会出现编译错误?

Mar*_*tin 9 c++ templates c++11

我正在使用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
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以从编译器解释这个错误的原因吗?

main.cpp:实例化'std :: unique_ptr make_unique(Args && ...)[用T = S; Args = {int}]':

main.cpp:11:58:需要'static std :: unique_ptr S :: create(Args && ...)[with Args = {int}]'

main.cpp:20:26:从这里要求

main.cpp:14:5:错误:'S :: S(int)'是私有的

 S(int) {}
 ^
Run Code Online (Sandbox Code Playgroud)

main.cpp:5:65:error:在这个上下文中返回std :: unique_ptr(new T {std :: forward(args)...});

                                                             ^
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 11

任何人都可以从编译器解释这个错误的原因吗?

int声明的构造函数private是为什么它会给出编译错误.请注意,构造函数将从make_unique(无法访问私有成员)调用,而不是从create.

但是,你可能想知道为什么第一次调用create()编译好,我认为这是因为GCC有bug.即使在这种情况下它也不应该编译,因为声明了默认构造函数private.Clang正确地给出了两个调用的错误(见这个).

无论如何,如果你想保留它们private,那就成为make_unique班上的朋友.