Sprint21
Sprint21

Reputation: 89

Implement move constructor with vector of pointers

I have vector of pointers in my class:

std::vector<Customer *> customers

Now I want to implement the move constructor. I'v find out that I can use std::move of std::vector. the problem is that I don't know if it will clear the old vector values. please if anyone can explain it to me.

my move constructor:

OpenTable::OpenTable(OpenTable&& other) : BaseAction(), tableId(other.tableId)
{
    customers=std::move(other.customers);
}

Upvotes: 0

Views: 1853

Answers (2)

einpoklum
einpoklum

Reputation: 132310

Your move constructor will do what you want, no need to clear anything

After std::move()'ing from an std::vector, the old vector will have 0 elements and no dynamic memory allocated for it. The newly-constructed vector takes that memory away. No need to clear any elements.

However, it should also be said that:

I have vector of pointers in my class:

This is a mistake... we're not using C++98 anymore. Raw pointers do not indicate who owns the memory, nor the lifespan of the object at the address. Now, you may get it right, but you may not. And what about a future maintainer of your code? Better not to leave it to chance: Use a smart pointer instead. Or - just place the actual objects in the vector. As comments suggest, if you're moving rather than copying the vector, you won't be making extra copies of the same objects.

More on this point in the Resource Management section of the C++ Core Programming Guidelines.

Upvotes: 3

eerorika
eerorika

Reputation: 238461

the problam is that I don't know if it will clear the old vector values.

Vector is guaranteed to be empty after it has been moved from.

customers=std::move(other.customers);

Instead of default constructing the member and then move-assigning it, it is better to move-construct the member directly in the member initialization list:

OpenTable::OpenTable(OpenTable&& other) : ..., customers(std::move(other.customers))

Although, it looks a lot like your constructor doesn't do anything different from the implicit move constructor, so you might use instead:

OpenTable::OpenTable(OpenTable&&) = default;

Even better, depending on the rest of your class, the move constructor may be implicitly declared, so you might not even need that defaulted declaration.

Upvotes: 2

Related Questions