I'm learning c++ and I recently learned (here in stack overflow) about the copy-and-swap idiom and I have a few questions about it. So, suppose I have the following class using a copy-and-swap idiom, just for example:
class Foo {
private:
int * foo;
int size;
public:
Foo(size_t size) : size(size) { foo = new int[size](); }
~Foo(){delete foo;}
Foo(Foo const& other){
size = other.size;
foo = new int[size];
copy(other.foo, other.foo + size, foo);
}
void swap(Foo& other) {
std::swap(foo, other.foo);
std::swap(size, other.size);
}
Foo& operator=(Foo g) {
g.swap(*this);
return *this;
}
int& operator[] (const int idx) {return foo[idx];}
};
My question is, suppose I have another class that have a Foo object as data but no pointers or other resources that might need custom copying or assignment:
class Bar {
private:
Foo bar;
public:
Bar(Foo foo) : bar(foo) {};
~Bar(){};
Bar(Bar const& other) : bar(other.bar) {};
Bar& operator=(Bar other) {bar = other.bar;}
};
Now I have a series of questions:
Are the methods and constructors as implemented above for the
Bar
class safe? Having used the copy-and-swap forFoo
make me sure that no harm can be done when assigning or copyingBar
?Passing the argument by reference in the copy constructor and in swap is mandatory?
Is it right to say that when the argument of
operator=
is passed by value, the copy constructor is called for this argument to generate a temporary copy of the object, and that it is this copy which is then swapped with*this
? If I passed by reference inoperator=
I would have a big problem, right?Are there situations in which this idiom fails to provide complete safety in copying and assigning
Foo
?
foo = new int[size]
before settingsize
– Rahalstd::vector<int>
as a member. Then you don't have to write the destructor and the copy operations in the first place. – Ache