Recently I encountered a serious bug while working on a project. It took me a whole day to figure out what causes the bug. Turns out, there is "bad design "(should i say?) in one library that I use.
Let's assume that we have this foo
class:
struct foo {
inline foo(int& i) : i_(i) { }
inline foo& operator=(const foo& that) {
if (this != &that) {
i_ = that.i_;
}
return *this;
}
inline
friend std::ostream& operator<<(std::ostream& os, const foo& f) {
os << f.i_;
return os;
}
private:
foo();
int& i_;
};
And here is the sample use of foo
:
#include <iostream>
#include <utility>
int main(int argc, char** argv) {
int x = 10;
int y = 100;
foo f1(x);
foo f2(y);
std::cout << "before swapping" << std::endl;
std::cout << "x = " << x << std::endl;
std::cout << "y = " << y << std::endl;
std::cout << "f1 = " << f1 << std::endl;
std::cout << "f2 = " << f2 << std::endl;
std::swap(f1, f2);
std::cout << "after swapping" << std::endl;
std::cout << "x = " << x << std::endl;
std::cout << "y = " << y << std::endl;
std::cout << "f1 = " << f1 << std::endl;
std::cout << "f2 = " << f2 << std::endl;
return 0;
}
And result:
before swapping
x = 10
y = 100
f1 = 10
f2 = 100
after swapping
x = 100
y = 100
f1 = 100
f2 = 100
I apologize if someone has already posted this issue before, if that's the case, please let me know, I'll delete this post.
In case no one has ever mentioned/encountered this issue before, please allow me to bring it up, to:
Ask if someone could come up with a solution to swap these two
foo
objects.To remind me/others that
std::swap
is not one-size-fits-all solution. So use it with caution!
Thank you!