可能是我错误地编码了我的类,但是当我使用移动构造函数而不是复制 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;
}
如何解决这个问题?
以下是移动值的方法:
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)