Avoid deallocate empty arrays?
IGotD-
nise at nise.com
Thu Dec 17 18:10:25 UTC 2020
On Thursday, 17 December 2020 at 17:46:59 UTC, Steven
Schveighoffer wrote:
>
> This isn’t correct. Can you post the code that led you to
> believe this?
>
> -Steve
Sure.
import std.algorithm;
import std.typecons;
import std.stdio;
struct Buffer
{
this(size_t size)
{
m_buffer.reserve = size;
}
void add(const void[] arr)
{
m_buffer ~= cast(ubyte[])arr;
}
string getSome()
{
if(m_buffer.length > 0)
{
return cast(string)m_buffer[0..$];
}
else
{
return "";
}
}
void remove(size_t size)
{
m_buffer = m_buffer.remove(tuple(0, size));
}
ubyte[] m_buffer;
}
void main()
{
Buffer b = Buffer(16);
b.add("aa");
writeln("b.m_buffer.length ", b.m_buffer.length, ",
b.m_buffer.capacity ", b.m_buffer.capacity);
string s = b.getSome();
assert(s == "aa");
b.remove(s.length);
writeln("b.m_buffer.length ", b.m_buffer.length, ",
b.m_buffer.capacity ", b.m_buffer.capacity);
}
This will print
b.m_buffer.length 2, b.m_buffer.capacity 31
b.m_buffer.length 0, b.m_buffer.capacity 0
capacity 0, suggests that the array has been deallocated.
More information about the Digitalmars-d-learn
mailing list