Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a variable length array or no?

Tags:

c++

arrays

string

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.

like image 659
user4048132 Avatar asked Jul 15 '26 15:07

user4048132


1 Answers

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.

like image 92
NPE Avatar answered Jul 18 '26 06:07

NPE