创建对象的第二个实例会更改整个类的行为(C ++) [英] Creating a second instance of an object changes whole class behavior (C++)
问题描述
我用C ++编写了一个Arduino库,其中包含一个迭代器类.如果我一直使用同一实例遍历它,那么它将按预期工作.如果我创建第二个实例,它将使存储的对象数量增加一倍.
I have written an Arduino library in C++ that contains an iterator class. If I iterate through it using the same instance all the time, it works as expected. If I create a second instance to do so, it will double the amount of stored objects.
WayPointStack wps = *(new WayPointStack());
wps.AddWP(1, 20);
wps.AddWP(2, 420);
WPCommand c1 = wps.GetNextWP(); // Stack length: 2, correct
c1 = wps.GetNextWP(); //
WPCommand c1 = wps.GetNextWP(); // Stack length: 4, not correct
WPCommand c2 = wps.GetNextWP(); //
WPCommand WayPointStack::GetNextWP()
{
Serial.println("Pointer = ");
Serial.println(pointer);
Serial.println("Length = ");
Serial.println(_length);
if (pointer < _length){
pointer++;
return _wp[pointer-1];
}
return *(new WPCommand(_END, 10000));
}
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length] = *(new WPCommand(target, time));
_length++;
}
WayPointStack::WayPointStack()
{
_wp = new WPCommand[arrSize];
_length = 0;
pointer = 0;
}
WPCommand::WPCommand(int target, int time)
{
_target = target;
_time = time;
}
有人可以向我解释吗?
推荐答案
WayPointStack wps = *(new WayPointStack());
必须
WayPointStack wps;
因为这足够了,并且可以消除内存泄漏
because it is enough and that removes the memory leak
在
WPCommand WayPointStack::GetNextWP()
{
...
return *(new WPCommand(_END, 10000));
}
您创建了另一个内存泄漏,可能是不返回该元素,但其地址允许您在出错时返回nullptr?
you create an other memory leak, may be do not return the element but its address allowing you to return nullptr on error ?
/*const ?*/ WPCommand * WayPointStack::GetNextWP()
{
Serial.println("Pointer = ");
Serial.println(pointer);
Serial.println("Length = ");
Serial.println(_length);
if (pointer < _length){
return &_wp[pointer++];
}
return nullptr;
}
否则使用静态var:
WPCommand WayPointStack::GetNextWP()
{
...
static WPCommand error(_END, 10000);
return error;
}
在
In
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length] = *(new WPCommand(target, time));
_length++;
}
您创建了另一个内存泄漏,只需要初始化条目即可:
you create an other memory leak, you just need to initialize the entry :
void WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return;
_wp[_length]._target = target, time));
_wp[_length]._time = time;
_length++;
}
当您无法添加新元素时,您不会发出错误信号,返回 bool 会在错误时返回false,并在添加时返回true:
you do not signal the error when you cannot add a new element, what about to return a bool valuing false on error and true when you can add :
bool WayPointStack::AddWP(int target, int time)
{
if (_length == arrSize)
return false;
_wp[_length]._target = target;
_wp[_length]._time = time;
_length++;
return true;
}
最后,为什么不将std::vector
用作_wp
Finally Why do you not use a std::vector
for _wp
这篇关于创建对象的第二个实例会更改整个类的行为(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!