这是一个可变长度的数组或没有? [英] Is this a variable length array or no?

查看:96
本文介绍了这是一个可变长度的数组或没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我试图创建一个没有动态内存的自定义字符串类,我使用的模板数组长度把戏。由于尺寸作为模板参数传递,它在编译时是已知的。因此,因此字符缓冲区[N] 不是一个变量长度数组。就是这种思维正确的路线?这里是code:

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.

推荐答案

是的,你的想法是正确的:缓存不是VLA

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.

一(潜在显著)皱纹是 string_test&LT; T,M&GT; string_test&LT; T,N&GT; 不同类型时米!= N

One (potentially significant) wrinkle is that string_test<T, m> and string_test<T, n> are different types when m != n.

在一般它似乎更适合简单地使用的std ::矢量&lt; T&GT; 。这将导致简单又正确的code与内存错误的小范围。

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.

这篇关于这是一个可变长度的数组或没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆