gpt4 book ai didi

c++ - 使用 std::allocator 和 std::move 防止释放的正确方法

转载 作者:行者123 更新时间:2023-11-28 05:49:50 26 4
gpt4 key购买 nike

正如标题所说,我想知道这是否是防止在 vector<T> a 中重新分配的正确方法搬家时vector<T> avector<T> b .

vector header :

template<class T, class A = std::allocator<T>>
class vector
{
typedef typename A::size_type size_type;

A alloc;
T* start;
T* end;

public:

explicit vector(size_type n, const T& val = T(), const A& =A());
vector(vector&&);
~vector();

};

构造函数:

注意:分配可以抛出 std::bad_alloc .

template<class T, class A>
vector<T,A>::vector(size_type n, const T& val, const A& a)
: alloc(a)
{

start = alloc.allocate(n); //allocate memory for n elements.
end = start + n;

for(auto p = start; p!=end; p++)
alloc.construct(p, val); //construct val at allocated memory.

}

移动构造函数:

问题:这是移动 vector v 的正确方法吗?

template<class T, class A>
vector<T,A>::vector(vector&& v)
:alloc(v.alloc) // copy the allocator in v.
{

start = std::move(v.start); // move the pointer previously returned by allocator.
end = std::move(v.end); // same boundary value.
v.start = v.end = nullptr; // nullptr to prevent deallocation when v is destroyed.
}

析构函数:

问题:根据cppreference , allocator::deallocate(p, n)从先前由 allocator 返回的指针释放内存和 n必须等于分配给的元素数。如果不是这种情况怎么办?我的回答是 allocator::deallocate如果指针或元素数量为 n,则不执行任何操作, 不等于之前对 allocator::allocate(n) 的调用.这是真的?

template<class T, class A>
vector<T, A>::~vector()
{
for(auto p = start; p!=end; p++)
alloc.destroy(p); //Destroy objects pointed to by alloc.

alloc.deallocate(start, end-start); //Deallocate memory.
}

最佳答案

Is this a proper way to move vector v?

看起来不错,但是 std::move 与指针是多余的。此外,您不会释放 end,因此您不需要将其设置为 null。

What if this is not the case? My answer would be that allocator::deallocate does nothing if the pointer or the number of elements, n, is not equal to previous call to allocator::allocate(n). Is this true?

不,行为未定义。您必须传递相同的 n

关于c++ - 使用 std::allocator 和 std::move 防止释放的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502745/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com