C++ 使用std::分配器和std::move防止释放的正确方法

C++ 使用std::分配器和std::move防止释放的正确方法,c++,c++11,C++,C++11,正如标题所说,我想知道当将向量a移动到向量b时,这是否是防止在向量a中解除分配的正确方法 向量头: 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

正如标题所说,我想知道当将
向量a
移动到
向量b
时,这是否是防止在
向量a
中解除分配的正确方法

向量头:

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();

};
移动构造函数:

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();

};
问:这是移动向量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.
}
这是移动向量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.
}
看起来不错,但是
std::move
与指针是多余的。此外,您不需要取消分配
end
,因此不需要将其设置为null

如果不是这样呢?我的答案是,如果指针或元素数n不等于对分配器::分配(n)的上一次调用,分配器::分配不会执行任何操作。这是真的吗

不,行为未定义。您必须通过相同的
n