In my attempt to create a custom string class without dynamic memory, I'm using the template array length trick. Because the size is passed as a template parameter, it is known at compile time. So therefore char buffer[n] is not a variable length array. Is this correct line of thinking? Here's code:
template<typename T, size_t n>
class string_test
{
using Type = T;
// Don't count NUL byte
size_t _size = n - 1;
char buffer[n]; // <--- variable length array?
public:
string_test(const char* str)
{
strcpy(buffer, str);
}
size_t size() const
{
return _size;
}
const char* c_str() const
{
return buffer;
}
};
template<typename T, size_t n>
string_test<T, n> make_string(const T (&str)[n])
{
return string_test<T, n>(str);
}
Hopefully by this method all memory is on stack and I don't run into any issues with new, delete and so on.
Yes, your thinking is correct: buffer is not a VLA.
Hopefully by this method all memory is on stack and I don't run into any issues with new, delete and so on.
This is also correct in the sense that you don't need to manage any memory by hand.
One (potentially significant) wrinkle is that string_test<T, m> and string_test<T, n> are different types when m != n.
In general it would seem more appropriate to simply use std::vector<T>. This will lead to straightforward yet correct code with little scope for memory errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With