Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ boost shared array swapping pointers (simple question)

I'm new to boost shared arrays.

There is existing code that declares two arrays:

boost::shared_array<unsigned char> src; 
boost::shared_array<unsigned char> dest; 

All I want to do is swap what each array is pointing to (src becomes dest, and dest becomes src). As I understand it, the shared_array.get() method returns a pointer to one of its elements (can be of any type).

So my added declaration is:

boost::shared_array<unsigned char> temp;

And my added code is:

temp.get() = src.get();
src.get() = dest.get();
dest.get() = temp.get();

Each of these lines fail; compile error is C2016: '=' : left operand must be l-value.

I am a C++ newbie, so I googled the error and see that that error message means that the left hand operand is not assignable. Yet the left hand sides are all pointers and pointers can be assigned to other pointers.

So I'm not sure what I'm doing wrong. Can someone please help me out?

Thanks in advance.

jbu

like image 815
jbu Avatar asked Mar 28 '26 08:03

jbu


1 Answers

The correct way to swap two shared_arrays (or most other Boost shared pointer types) is to use the swap member function:

src.swap(dest);

This swaps the pointers and reference counts used by each of the shared_arrays:

void swap(shared_array<T> & other)
{
    std::swap(px, other.px);
    pn.swap(other.pn);
}
like image 173
James McNellis Avatar answered Mar 29 '26 21:03

James McNellis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!