Is it a variable length array or not?

In my attempt to create a custom heapless string class, I use the template array length trick. Since the size is passed as a template parameter, it is known at compile time. Therefore, char buffer[n]

it is not a variable length array. Is this the correct line of thinking? Here's the 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 with this method all the memory is on the stack and I don't run into problems with new ones, delete, etc.

+3


source to share


2 answers


Yes, your thinking is correct: buffer

it is not a VLA.

Hopefully with this method all the memory is on the stack and I don't run into problems with new ones, delete, etc.

It is also correct in the sense that you do not need to manually manage memory.



One (potentially significant) wrinkle is that string_test<T, m>

and string_test<T, n>

are different types when m != n

.

Overall it would be more convenient to use std::vector<T>

. This will result in simple but correct code with few memory errors.

+3


source


Code and thinking are not wrong; and will work as it is.

I would question the motive and the means to achieve it. The class is unsafe in terms of bounds checking. For example, if ctor is a larger capacity string, BANG.



Managing heap memory is as efficient as it gets, and I don't foresee performance issues for 99.99% of applications. If you are REALLY trying to squeeze the latest CPU performance hit, then using STL is probably not the right choice. You should limit yourself to classic C-style programming with hand-crafted optimized algorithms.

Finally, I second PaulMcKenzie above, if you want to customize memory management for any of the containers (including the string) use a std class with a custom allocator. You can build an auto-buffer allocator on the stack and force it to use that buffer.

0


source







All Articles