adadaae12313412 adadaae12313412 - 1 month ago 8
C++ Question

How to use move constructor with 2d array (**<type>)?

It might be that I have coded my class incorrectly, but when I use the move constructor instead of the copy cotr (as one of the overloads not instead to be precise), my program crushes:

For example:

class Sample
{
int a;
int **b;
//constructor declarations
}


And in the .cpp file:

Sample::Sample(Sample &&other)
: a(a), b(b)
{
for (int i = 0; i < a; i++)
other.b[i] = nullptr;
other.b = nullptr;
other.a = 0;
}


How to fix this issue?

Answer

Here is how you could move the values:

#include <utility>
#include <iostream>

class Sample
{
    int a;
    int **b;
public:
    Sample(int a, int** b) : a{a}, b{b} {}
    Sample(Sample &&other);
    // still missing a destructor that will get rid of the new'd ints
    void print();
};

Sample::Sample(Sample &&other)
    : a(other.a), b(other.b)
{
    //for(int i = 0; i < a; i++)
    //  other.b[i] = nullptr; // this should not be done, the new b has a pointer to these values
    other.b = nullptr;
    other.a = 0;
}

void Sample::print()
{
    if(a == 0 && b == nullptr)
        std::cout << "this object is empty!";
    for(size_t i{0}; i < a; ++i) {
        std::cout << *b[i] << " ";
    }
    std::cout << '\n';
}

int main()
{
    Sample s{5,{new int*[5]{new int{0}, new int{1}, new int{2}, new int{3}, new int{4}}}};
    auto c{std::move(s)};
    // c now has c.b as a pointer an array of pointers
    s.print();
    c.print();
    return 0;
}
Comments