Skip to content

Instantly share code, notes, and snippets.

@borisbat
Last active December 19, 2015 03:28
Show Gist options
  • Save borisbat/5890068 to your computer and use it in GitHub Desktop.
Save borisbat/5890068 to your computer and use it in GitHub Desktop.
Simple storage.
#include <iostream>
#include <vector>
#include <functional>
#include <initializer_list>
#define USE_EMPLACE 1
#define USE_UREF 1
using namespace std;
template <typename TT>
class Storage
{
public:
Storage() {}
Storage(Storage && x) {
data=x.data;
x.data=nullptr;
}
Storage(const Storage & x) {
data = new TT(*(x.data));
}
Storage & operator = (const Storage & x) {
if ( data ) delete data;
data = new TT(*(x.data));
return *this;
}
~Storage() {
if ( data ) delete data;
}
#if USE_EMPLACE
template <typename ...Params>
void set(Params&&... params) {
if ( data ) delete data;
data = new TT(std::forward<Params>(params)...);
}
#elif USE_UREF
template <typename OTT>
void set(OTT && value) {
if ( data ) delete data;
data = new TT(forward<OTT>(value));
}
#else
void set(const TT & value) {
if ( data ) delete data;
data = new TT(value);
}
void set(TT && value) {
if ( data ) delete data;
data = new TT(move(value));
}
#endif
protected:
TT * data = nullptr;
};
class Report
{
public:
Report(int, float) : i_am_dead(false) { cout << " Report(int,float);" << endl; }
Report() : i_am_dead(false) { cout << " Report();" << endl; }
Report(const Report & ) : i_am_dead(false) { cout << " Report(const Report&);" << endl; };
Report(Report && h) : i_am_dead(false) { cout << " Report(&&);" << endl; h.i_am_dead = true; }
Report & operator = (const Report&) { cout << " Report::=(const Report&);" << endl; return *this; };
~Report() { cout << " ~Report() i_am_dead=" << i_am_dead << endl; }
bool i_am_dead;
};
Report f(int bla) {
return Report();
}
int main(int argc, const char * argv[])
{
cout << "set(Report());" << endl;
{
Storage<Report> xxx;
xxx.set(Report());
}
/*
set(Report());
Report();
Report(&&);
~Report() i_am_dead=1
~Report() i_am_dead=0
*/
cout << "set(a);" << endl;
{
Storage<Report> xxx;
Report a;
xxx.set(a);
}
/*
set(a);
Report();
Report(const Report&);
~Report() i_am_dead=0
~Report() i_am_dead=0
*/
cout << "set(f(1));" << endl;
{
Storage<Report> xxx;
xxx.set(f(1));
}
/*
set(f(1));
Report();
Report(&&);
~Report() i_am_dead=1
~Report() i_am_dead=0
*/
#if USE_EMPLACE
cout << "set(1,2.0f);" << endl;
{
Storage<Report> xxx;
xxx.set(1,2.0f);
}
/*
set(1,2.0f);
Report(int,float);
~Report() i_am_dead=0
*/
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment