Created
January 16, 2018 18:27
-
-
Save funvill/a8d1a6c0ad8c0d90de3f97ffe2786014 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CopyInsertExample.cpp : Defines the entry point for the console application. | |
// | |
#include "stdafx.h" | |
#include "vector" | |
// A counter for the creation of the class Foo | |
int FooCounter; | |
class Foo | |
{ | |
public: | |
int myCounter; | |
Foo() { | |
FooCounter++; | |
printf("Foo::Foo New FooCounter = %d\n", FooCounter); | |
myCounter = FooCounter; | |
} | |
~Foo() { | |
printf("Foo::~Foo Delete FooCounter = %d\n", FooCounter); | |
FooCounter--; | |
} | |
virtual void Print() { | |
printf("Foo::Print myCounter = %d\n", myCounter); | |
} | |
Foo(const Foo & rhs) { | |
this->myCounter = rhs.myCounter; | |
printf("Foo::Foo() Copy Foo. myCounter = %d\n", myCounter); | |
} | |
}; | |
class FooChild : public Foo | |
{ | |
public: | |
int extraStuff = 0; | |
void Print() { | |
printf("FooChild::Print: myCounter = %d\n", myCounter); | |
} | |
}; | |
class FooContainer | |
{ | |
public: | |
std::vector<Foo *> m_objects; | |
FooContainer() { | |
m_objects.reserve(100); // Remove the confusion of resizing of the vector on vector.push_back | |
} | |
void Insert(Foo * object) { | |
printf("FooContainer::Insert object.myCounter = %d\n", object->myCounter); | |
this->m_objects.push_back(object); | |
} | |
// Run print on all the objects in this container. | |
void Print() { | |
for (size_t offset = 0; offset < this->m_objects.size(); offset++) { | |
m_objects[offset]->Print(); | |
} | |
} | |
}; | |
void FillContainer(FooContainer *container) | |
{ | |
Foo a; | |
FooChild b; | |
container->Insert(&a); | |
container->Insert(&b); | |
container->Print(); | |
} | |
int main() | |
{ | |
FooCounter = 0; | |
FooContainer container; | |
FillContainer(&container); | |
container.Print(); // Access violation because Foo and FooChild have been deleted in FillContainer() | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment