[英]How to free the heap memory allocated for String class member without deleting the object
I have a class BLEValue
that has a member called m_accumulation
of type String
.我有一个 class
BLEValue
,它有一个名为m_accumulation
的String
类型的成员。 I use this member to accumulate the data (15000 byte) received over bluetooth until the whole data is received and then this m_accumulation
will be read and the data it saves is no longer needed therefore it is set to ""
.我使用这个成员来累积通过蓝牙接收到的数据(15000 字节),直到接收到整个数据,然后这个
m_accumulation
将被读取并且不再需要它保存的数据因此它被设置为""
。
void BLEValue::addPart(uint8_t *pData, size_t length)
{
log_v("Adding part to m_accumulation. Current free heap: %d", ESP.getFreeHeap());
m_accumulation += std::string((char *)pData, length);
}
void BLEValue::clear()
{
m_accumulation = "";
m_accumulation.clear(); // I think it does the same as the previous line
}
The problem is that the memory allocated in the heap for this class member will not get free again after emptying m_accumulation
.问题是在堆中为这个 class 成员分配的 memory 在清空
m_accumulation
后将不会再次释放。 I can check this using the function ESP.getFreeHeap()
.我可以使用 function
ESP.getFreeHeap()
检查这个。 I think this is so because the object of the BLEValue
class is still alive and therefore the heap memory allocated for it will be not be freed until the object is killed.我认为这是因为 BLEValue class 的
BLEValue
仍然存在,因此分配给它的堆 memory 在 object 被杀死之前不会被释放。 Is it true?是真的吗?
Is there a way to empty the heap memory allocated to this String
after reading its value without deleting the BLEValue
object completely?有没有办法在读取它的值后清空分配给这个
String
的堆 memory 而不完全删除BLEValue
object?
Clear marks the string as having size 0, but the internal array is not necessarily changed. Clear 将字符串标记为大小为 0,但不一定会更改内部数组。 To force the string to free it's memory, use shrink_to_fit after clear.
要强制释放字符串 memory,请在清除后使用shrink_to_fit 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.