std::vector 的 posix_memalign

发布于 2024-08-23 18:26:47 字数 206 浏览 4 评论 0原文

有没有办法在不先创建向量的本地实例的情况下对 std::vector 进行 posix_memalign ? 我不知道该怎么说

sizeof(std::vector<type>(n)) 

我遇到的问题是我需要告诉 posix_memalign 要分配多少空间,但在没有实际创建新向量的情况下

。谢谢

Is there a way to posix_memalign a std::vector without creating a local instance of the vector first?
The problem I'm encountering is that I need to tell posix_memalign how much space to allocate and I don't know how to say

sizeof(std::vector<type>(n)) 

without actually creating a new vector.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

憧憬巴黎街头的黎明 2024-08-30 18:26:47

嗯,这里有两种尺寸。矢量本身通常只不过是一个或两个指向某些已分配内存的指针,以及跟踪大小和容量的无符号整数。还有分配的内存本身,这就是我认为你想要的。

您想要做的是创建一个向量将使用的自定义分配器。到时候,它将使用您的分配器,您可以拥有自己的特殊功能。我不会详细介绍分配器的完整详细信息,但具体细节如下:

template <typename T>
struct aligned_allocator
{
    // ...

    pointer allocate(size_type pCount, const_pointer = 0)
    { 
        pointer mem = 0;
        if (posix_memalign(&mem, YourAlignment, sizeof(T) * pCount) != 0)
        {
            throw std::bad_alloc(); // or something
        }

        return mem;
    }

    void deallocate(pointer pPtr, size_type)
    { 
        free(pPtr);
    }

    // ...
};

然后你可以像这样使用它:

typedef std::vector<T, aligned_allocator<T> > aligned_T_vector;

aligned_T_vector vec;
vec.push_back( /* ... */ ); // array is aligned

但是重申第一点,无论它包含多少个元素,向量的大小都是相同的,因为它只指向一个缓冲区。仅该缓冲区的大小发生变化。

Well, there are two sizes here. The vector itself is typically no more than a pointer or two to some allocated memory, and unsigned integers keeping track of size and capacity. There is also the allocated memory itself, which is what I think you want.

What you want to do is make a custom allocator that the vector will use. When it comes time, it will use your allocator and you can have your own special functionality. I won't go over the full details of an allocator, but the specifics:

template <typename T>
struct aligned_allocator
{
    // ...

    pointer allocate(size_type pCount, const_pointer = 0)
    { 
        pointer mem = 0;
        if (posix_memalign(&mem, YourAlignment, sizeof(T) * pCount) != 0)
        {
            throw std::bad_alloc(); // or something
        }

        return mem;
    }

    void deallocate(pointer pPtr, size_type)
    { 
        free(pPtr);
    }

    // ...
};

And then you'd use it like:

typedef std::vector<T, aligned_allocator<T> > aligned_T_vector;

aligned_T_vector vec;
vec.push_back( /* ... */ ); // array is aligned

But to reiterate the first point, the size of a vector is the same regardless of how many elements it's holding, as it only points to a buffer. Only the size of that buffer changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文