加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么会收到编译错误?

发布时间:2020-12-16 03:18:42 所属栏目:百科 来源:网络整理
导读:我使用GCC 4.8来编译下面的代码: #include memorytemplatetypename T,typename ...Args std::unique_ptrT make_unique(Args ...args) { return std::unique_ptrT(new T{std::forwardArgs(args)...});}struct S { templateclass... Args static std::unique_
我使用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
}

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

main.cpp: In instantiation of ‘std::unique_ptr make_unique(Args&&
…) [with T = S; Args = {int}]’:

main.cpp:11:58: required from ‘static std::unique_ptr
S::create(Args&& …) [with Args = {int}]’

main.cpp:20:26: required from here

main.cpp:14:5: error: ‘S::S(int)’ is private

06001

main.cpp:5:65: error: within this context
return std::unique_ptr(new T{std::forward(args)…});

06002

解决方法

Can anyone explain me the reason of this error from the compiler?

使用int的构造函数被声明为private,这就是为什么它提供编译错误.请注意,构造函数正在从make_unique(不能访问私有成员)中调用,而不是从创建.

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

无论如何,如果你想让他们保持私密,那么让make_unique成为班级的朋友.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读