Reputation: 11
I have my own class Vector which implements Move constructor, Move assignment operator and method push_back for rvalue
template<typename T>
class Vector
{
private:
T* buffer;
size_t size;
size_t capacity;
public:
Vector(size_t s) {
size = 0;
capacity = s;
buffer = new T[capacity];
}
//Move constructor
Vector(Vector&& tmp): buffer(tmp.buffer),
size(tmp.size),
capacity(tmp.capacity)
{
tmp.buffer = nullptr;
}
//Move assignment operator
Vector& operator=(Vector&& tmp) {
size = tmp.size;
capacity = tmp.capacity;
buffer = std::move(tmp.buffer);
tmp.buffer = nullptr;
return *this;
}
void push_back(const Vector<T>& v) {
if (size >= capacity)
reserve(capacity + 5);
buffer[size++] = v;
}
//push_back for rvalue
void push_back(T&& v) {
if (size >= capacity)
reserve(capacity + 5);
buffer[size++] = std::move(v);
}
~Vector() {
delete[] buffer;
}
In method push_back(T&& v) the line
buffer[size++] = std::move(v);
uses Move assignment operator. How can I change code so that it will use Move constructror ?
Upvotes: 1
Views: 340
Reputation: 2121
Use placement new:
new (&buffer[size++]) T (std::move(v));
Here is a complete example: http://cpp.sh/6s4i3
Upvotes: 3
Reputation: 31
i was moving ball but if there is something usefull for you
#pragma once
class movement
{
private:
Ball *b;
int size;
public:
movement(void)
{
size=0;
}
Ball getBall(int i)
{
return b[i];
}
void insertBall(Ball n)
{
Ball *temp=new Ball[size+1];
for (int i = 0;i<size; i++)
{
temp[i]=b[i];
}
temp[size]=n;
delete []b;
b=temp;
size++;
}
void update(Ball food,Ball b)
{
for (int i = 0; i < size; i++)
{
//if ((b->getPoint().getX() == b->getPoint().getY())
if (food.getPoint().getX == b.getPoint().getX() && food.getPoint().getY == b.getPoint().getY())
{
insertBall(b);
}
}
}
};
Upvotes: 0