C++ 如何将移动构造函数与二维数组(**<;type>;)一起使用?

C++ 如何将移动构造函数与二维数组(**<;type>;)一起使用?,c++,C++,可能是我对类的编码不正确,但当我使用move构造函数而不是copy cotr(确切地说是重载之一)时,我的程序会崩溃: 例如: class Sample { int a; int **b; //constructor declarations } 在.cpp文件中: Sample::Sample(Sample &&other) : a(a), b(b) { for (int i = 0; i < a; i++) ot

可能是我对类的编码不正确,但当我使用move构造函数而不是copy cotr(确切地说是重载之一)时,我的程序会崩溃:

例如:

class Sample
{
    int a;
    int **b;
    //constructor declarations
}
在.cpp文件中:

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;
}
Sample::Sample(示例和其他)
:a(a),b(b)
{
for(int i=0;i

如何解决这个问题?

我将重述我上面的评论,并将其作为答案。您复制了“b”指针,但修改了指针指向的值。新对象将获得正确的指针“b”,但指针指向的值也将被修改,在这种情况下,它将指向数字零。您正在使用指向指针的指针,因此在某个时刻,您的新对象可能会尝试取消对指针的引用,并且由于取消对空指针的引用,会发生不好的情况。

以下是移动值的方法:

#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;
}
#包括
#包括
类样本
{
INTA;
国际**b;
公众:
样本(inta,int**b):a{a},b{b}
样品(样品和其他);
//仍然缺少一个析构函数,该析构函数将清除新的整数
作废打印();
};
样本::样本(样本和其他)
:a(其他.a),b(其他.b)
{
//for(int i=0;istd::cout
n
的值是多少?我做了一些轻微的编辑,因为我从我的项目中复制了代码,我忘了编辑该部分,对不起。您复制了指针值“b”,但您修改了指针指向的值并将其设置为0,因此新对象“b”指针也将指向零。因此,如果执行类似于t的操作,您的程序可能会崩溃所以我应该删除{}之间的所有内容?还是应该隐式复制每一行?移动构造函数不必将源对象转换为mush。您能为我的构造函数提供一个编辑,使其执行它应该执行的操作吗,因为我仍然不确定如何执行该操作?我对我的类进行了一些编辑,即使没有std::move,它也可以工作。谢谢!