Skip to content

Instantly share code, notes, and snippets.

@rgoulter
Last active December 28, 2015 06:59
Show Gist options
  • Save rgoulter/7461585 to your computer and use it in GitHub Desktop.
Save rgoulter/7461585 to your computer and use it in GitHub Desktop.
IDK: C++ Rule of Three, and std::vector.
Construct some objects:
Constructor 1
Constructor 2
Constructor 3
Do some assignment:
Assignment of Foo#1 to Foo#3
Copy-constructor?
Copy Constructor Foo#4 from Foo#2
Some vector stuff:
Copy Constructor Foo#5 from Foo#1
Copy Constructor Foo#6 from Foo#2
Copy Constructor Foo#7 from Foo#5
Destructor Foo#5
Get value from vector:
Copy Constructor Foo#8 from Foo#7
Retrieved value is 1
Can we use pointers instead?
Get value from vector:
Retrieved value is 1
Destructor Foo#8
Destructor Foo#7
Destructor Foo#6
Destructor Foo#4
Destructor Foo#3
Destructor Foo#2
Destructor Foo#1
#include <iostream>
#include <vector>
using namespace std;
class Foo {
public:
Foo(int n) {
numObjects++;
id = numObjects;
cout << "Constructor " << id << endl;
value = n;
}
// Copy-Constructor
Foo(const Foo& other) {
numObjects++;
id = numObjects;
cout << "Copy Constructor Foo#" << id << " from "<< other << endl;
value = other.value;
}
// Destructor
~Foo() {
cout << "Destructor Foo#" << id << endl;
}
// Copy Assignment operator
Foo& operator=(const Foo& other) {
cout << "Assignment of " << other << " to Foo#" << id << endl;
value = other.value;
return *this;
}
int data() {
return value;
}
private:
friend ostream& operator<< (ostream& os, const Foo& foo) {
os << "Foo#" << foo.id;
return os;
}
int value;
int id;
static int numObjects;
};
int Foo::numObjects = 0;
int main() {
cout << "Construct some objects:" << endl;
Foo f1(1);
Foo f2(2);
Foo f3 = Foo(3);
cout << endl;
cout << "Do some assignment:" << endl;
f3 = f1;
cout << endl;
cout << "Copy-constructor?" << endl;
Foo f4(f2);
cout << endl;
cout << "Some vector stuff:" << endl;
vector<Foo> fooVec;
fooVec.push_back(f1);
fooVec.push_back(f2);
cout << "Get value from vector:" << endl;
Foo f5 = fooVec[0];
cout << "Retrieved value is " << f5.data() << endl;
cout << endl;
cout << "Can we use pointers instead?" << endl;
vector<Foo*> fooRefVec;
fooRefVec.push_back(&f1);
fooRefVec.push_back(&f2);
cout << "Get value from vector:" << endl;
Foo* f6 = fooRefVec[0];
cout << "Retrieved value is " << f6->data() << endl;
cout << endl;
return 0;
}
@rgoulter
Copy link
Author

@rgoulter
Copy link
Author

http://stackoverflow.com/questions/817263/is-it-possible-to-create-a-vector-of-pointers
Good comments about this issue, for a question asked by a newbie.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment