Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving array of unique_ptr<T> in a recursive data structure

Attempting to compile the following code results in the following compile error:

error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function

My understanding is that the array 'm_children' should be movable since the type pointed to by unique_ptr has a move constructor defined.

Unless this is an error being caused by the recursive nature of the class or some element of move semantics that I have overlooked?

#include <array>
#include <memory>
#include <iostream>

class OctreeNode{
public:
    OctreeNode(){ };
    OctreeNode(OctreeNode&& other) : m_children(std::move(other.m_children)){};
private:
    std::array<std::unique_ptr<OctreeNode>, 8> m_children;
};

int main(int argc, char* argv[])
{
    OctreeNode T;
    std::cout << "Success!" << std::endl;
    return 0;
}
like image 253
Edward J Brown Avatar asked Feb 09 '23 13:02

Edward J Brown


2 Answers

It seems like in vs2013 that definition of std::array in the <array> header doesn't include a move constructor or move assignment operator.

Under C++ rules these should be automatically generated (and so unnecessary to manually define), but msvc didn't include implicit generation of those until vs2015.

like image 113
Mike Vine Avatar answered Feb 13 '23 02:02

Mike Vine


according to the error message, it doesn't call the move constructor of the unique_ptr. Instead, it calls the copy-constructor of it which is not exist. So, iterate over the unique_ptrs and call move constructor explicitly.

    int i = 0;
    for(auto& x : other.m_children)
        m_children[i++] = std::move(x);

Btw, normally it should work because std::array is movable if and only if the element that it stores is movable too. In you case, unique_ptr is movable so that it shouldn't be problem. Please refer to below link for more detailed discussion

Is std::array movable?

like image 40
Validus Oculus Avatar answered Feb 13 '23 04:02

Validus Oculus