Skip to content

Instantly share code, notes, and snippets.

@ydm
Created March 16, 2015 16:34
Show Gist options
  • Save ydm/200dbf93867054f1feac to your computer and use it in GitHub Desktop.
Save ydm/200dbf93867054f1feac to your computer and use it in GitHub Desktop.
Try / catch always creates copy of thrown object
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <string>
class Humanizator
{
public:
Humanizator () : next_ (0), ps_ () {}
virtual ~Humanizator () {}
int name (const void *p)
{
if (ps_.find (p) == ps_.end ())
ps_[p] = next_++;
return ps_[p];
}
private:
int next_;
std::map<const void *, int> ps_;
};
Humanizator g_humanizator;
std::function<int (const void*)> name = std::bind (&Humanizator::name, &g_humanizator, std::placeholders::_1);
class A
{
public:
A () {std::cout << "NEW: " << name (this) << std::endl;}
A (const A& other) {std::cout << "COPY: " << name (&other) << " -> " << name (this) << std::endl;}
virtual ~A () {std::cout << "DELETE: " << name (this) << std::endl;}
};
int main()
{
using namespace std;
// Try / catch always creates a copy of the object by standard, right?
try
{
A a;
cout << "TRY: " << name (&a) << endl;
throw a;
}
catch (A& ex)
{
cout << "CATCH: " << name (&ex) << endl;
}
cout << "END" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment