Skip to content

Instantly share code, notes, and snippets.

/swap.cpp Secret

Created March 23, 2015 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/73ccac277baee8841470 to your computer and use it in GitHub Desktop.
Save anonymous/73ccac277baee8841470 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string name;
public:
A(string newName) {
name = newName;
}
void SayHi() {
cout << "Hello from " << name << "\n";
}
};
void swap(A* a1, A* a2) {
A temp = *a1;
*a1 = *a2;
*a2 = temp;
}
int main() {
A *a1 = new A("Dog");
A *a2 = new A("Cat");
A *a3 = a1;
swap(a1, a2);
a1->SayHi();
a2->SayHi();
a3->SayHi();
if (a3 == a2) {
cout << "Real pass-by-reference swap\n";
} else {
cout << "Fake pass-by-value swap\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment