Stopped memory leak with transferring tokens

This commit is contained in:
Pasha Bibko
2025-07-23 18:22:24 +01:00
parent 783d259995
commit 6a534ba635
2 changed files with 36 additions and 4 deletions

View File

@@ -92,6 +92,16 @@ namespace LXC::Lexer
// Constructor to set the data of the token for more complex token types //
Token(const LexerContext& ctx, uint32_t start, unsigned short len, TokenType _type);
// Copy constructor //
Token(const Token& other);
// Move constructor (transfers memory allocated) //
Token(Token&& other) noexcept;
// Cannot use these as members are const //
Token& operator=(const Token&) = delete;
Token& operator=(Token&&) = delete;
// Deconstructor to clean up the allocated memory //
~Token();

View File

@@ -21,14 +21,35 @@ namespace LXC::Lexer
}
}
// Copy constructor //
Token::Token(const Token& other) :
type(other.type), length(other.length), index(other.index), contents(nullptr)
{
if (other.contents != nullptr)
{
size_t len = std::strlen(other.contents) + 1; // Adds one for null-terminator
contents = new char[len];
std::memcpy(contents, other.contents, len);
}
}
// Move constructor (transfers memory allocated) //
Token::Token(Token&& other) noexcept :
type(other.type), length(other.length), index(other.index), contents(other.contents)
{
// Stops the other from thinking it owns the memory //
other.contents = nullptr;
}
// Destructor to clean up the memory of the token that can be allocated //
Token::~Token()
{
// Frees any allocated memory //
//if (contents != nullptr)
// delete[] contents;
contents = nullptr;
if (contents != nullptr) _UNLIKELY
{
delete[] contents;
contents = nullptr;
}
}
// Helper macro for converting type to string //
@@ -82,6 +103,7 @@ namespace LXC::Lexer
std::ostringstream os;
os << std::setw(25) << std::left << TokenTypeToCStr(type) << " | ";
// Prints the contents if they are not null //
if (contents != nullptr)
os << std::setw(25) << std::left << std::string('"' + std::string(contents) + '"');
else