Skip to content

Instantly share code, notes, and snippets.

@jlschrag
Created May 26, 2022 03:19
Show Gist options
  • Save jlschrag/76d0fd2865b7426590ffec0710b68ae6 to your computer and use it in GitHub Desktop.
Save jlschrag/76d0fd2865b7426590ffec0710b68ae6 to your computer and use it in GitHub Desktop.
void BetterApproach()
{
{
shared_ptr<TooManyResponsibilities> root(new TooManyResponsibilities());
{
shared_ptr<Responsibility1> first = static_pointer_cast<Responsibility1>(root);
{
shared_ptr<Responsibility2> second = static_pointer_cast<Responsibility2>(root);
cout << "'second' going out of scope..." << endl;
}
cout << "'first' going out of scope..." << endl;
}
cout << "'root' going out of scope..." << endl;
}
cout << "All done..." << endl;
}
void DoubleFreeSilentFail()
{
InnocentBystander* bystander;
{
TooManyResponsibilities* root = new TooManyResponsibilities();
{
shared_ptr<Responsibility1> first(root);
bystander = new InnocentBystander(first);
{
shared_ptr<Responsibility2> second(root);
cout << "'second' going out of scope..." << endl;
}
cout << "'first' going out of scope..." << endl;
}
cout << "'root' going out of scope..." << endl;
}
cout << "All done..." << endl;
}
class InnocentBystander
{
public:
InnocentBystander(shared_ptr<Responsibility1> res1) : m_Res1(res1) {}
private:
shared_ptr<Responsibility1> m_Res1;
};
//A couple segregated interfaces, each capturing one responsibility of the TooManyResponsibilities class
struct Responsibility1
{
virtual void DoThing1() = 0;
virtual ~Responsibility1() {};
};
struct Responsibility2
{
virtual void DoThing2() = 0;
virtual ~Responsibility2() {};
};
//The first step towards splitting up TooManyResponsibilities
class TooManyResponsibilities : public Responsibility1, public Responsibility2
{
public:
TooManyResponsibilities() {}
~TooManyResponsibilities() { cout << "Destructor" << endl; }
void DoThing1() override {}
void DoThing2() override {}
};
//A legacy "god" class
class TooManyResponsibilities
{
public:
TooManyResponsibilities() {}
~TooManyResponsibilities() {}
void DoThing1() {}
void DoThing2() {}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment