I am struggling to write (my first) swap function for a struct that contains a pointer array.
struct Foo
{
unsigned int Count;
int* Items;
Foo()
{
Count = 0;
Items = 0;
}
Foo(const Foo& foo)
{
Items = 0;
swap(foo); // cannot convert argument 1 from 'const Foo' to 'Foo *'
}
Foo(const unsigned int itemCount)
{
Count = itemCount;
Items = new int[itemCount];
for (int i = 0; i < itemCount; i++)
{
Items[i] = 123;
}
}
Foo& operator=(const Foo& foo)
{
swap(foo); // cannot convert argument 1 from 'const Foo' to 'Foo *'
return *this;
}
void swap(Foo* foo)
{
unsigned int a(Count);
int* b(Items);
Count = foo->Count;
Items = foo->Items;
foo->Count = a;
foo->Items = b;
}
~Foo()
{
delete[] Items;
}
};
Can anyone please help me with the syntax?
The reason I am doing this is to help me understand how this can work with pointer arrays?
I have read online that it is exception safe as it doesn't allocate new memory to do it? Surely
a
andb
are both allocated memory and can therefore fail if memory isn't available?
Edit: Based on the answer by lucacox...
void swap(Foo* foo1, Foo* foo2)
{
unsigned int a(foo1->Count);
int* b(foo1->Items);
foo1->Count = foo2->Count;
foo1->Items = foo2->Items;
foo2->Count = a;
foo2->Items = b;
}
Called like this...
swap(&foo, this); // cannot convert argument 1 from 'const Foo' to 'Foo *'
I still get a const convert error?