Daniel
Daniel

Reputation: 2726

How to use unique_ptr with std::copy?

I googled and found nothing. I guess I just don't know how to type the right question.

Okay, my simple MemoryBlock class has two member data, int size and int* data. So to build a copy constructor, I use std::copy to do the memory copy. Now I would like to try the C++ smart pointer to replace the raw pointer. Say using the unique_ptr<int> data. What is the equivalence of the following code? Because now, rhs.data + size won't work.

std::copy(rhs.data, rhs.data + size, data);

Upvotes: 8

Views: 11005

Answers (2)

roalz
roalz

Reputation: 2788

You can use the std::unique_ptr<>::get() function, that returns a pointer to the managed object or nullptr if no object is owned.

I.e.:

std::copy(rhs.data.get(), rhs.data.get() + size, data.get());

As also commented by NathanOliver, another option is to replace raw memory pointer owned by unique_ptr with std::vector altogether.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311166

First of all you have to allocate the array for the created object and then you can copy values to it. For example

MemoryBlock( const MemoryBlock &m ) : size( m.size ), data( new int[m.size] )
{
    std::copy(m.data.get(), m.data.get() + m.size, data.get());
}

Take into account that the member data data must be declared like

std::unique_ptr<int[]> data;

If you want to add the move constructor to the class you can define it the following way

MemoryBlock( MemoryBlock &&m ) : size( 0 ), data( nullptr )
{
    std::swap( m.size, size );
    std::swap( m.data, data );
}

Upvotes: 8

Related Questions