无法访问私有成员-模板和std::unique_ptr

3

I have the following code:

#include <memory>

template<typename T, size_t Level>
class Foo
{
    friend class Foo<T, Level + 1>;
    typedef std::unique_ptr<T> ElmPtr;
    typedef std::unique_ptr<Foo<ElmPtr, Level - 1>> NodePtr;        

    public:
    Foo() {
        // no errors
        auto c = children;
    }

    Foo(int n) {
        // !!! compiler error !!!
        auto c = children;
    }

    std::array<NodePtr, 4> children;            
};

template<typename T>
class Foo<T, 0>
{
    friend class Foo<T, 1>;

    public:
    Foo() {}
};

int main()
{
    Foo<int, 1> foo1;
}

我收到了以下错误信息:

错误 C2248: 'std::unique_ptr<_Ty>::unique_ptr':无法访问类中声明的私有成员'std::unique_ptr<_Ty>'

为什么会出现这个错误?我该如何解决这个问题?

4
两个构造函数对我来说都会报错,因为你试图复制一个不可复制的 std::unique_ptr。你必须要么从中移动其值,要么将其绑定到一个引用上。 - David G
1
你需要在两个地方使用 auto c = std::move(children);。我们无法告诉你为什么它在一个地方编译而在另一个地方没有,因为你没有提供 SSCCE - Praetorian
1
@Praetorian:这不是一个SSCCE吗?它很短,可以编译。但可惜缺少了正确的#include <...>语句,不过这已经比我们通常得到的要好得多了。 - Bill Lynch
1
g++ 4.8.2 在默认构造函数中显示错误。 - user2249683
@Nick:问题在于你提供的代码在我能找到的任何编译器中都没有出现你所描述的错误。不管是clang、GCC还是MSVC都没有。SSCCE中的第二个C代表“Correct”,其中一个意思是“示例会导致需要解决的确切错误消息。”http://sscce.org/如果没有这个,我们最终会在这里解决代码,并提供一种对你没有帮助的修复方法。 - Mooing Duck
1个回答

5

您拥有:

auto c = children;

位置:

std::array<std::unique_ptr<T>, N> children;            

那需要复制unique_ptr,但unique_ptr不可复制。不过你可以取得children的引用:

auto& c = children; // OK 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接