Box <T>
是一个智能指针,指向在类型为T的堆上分配的数据。Box <T>
允许将数据存储在堆而不是栈上。Box
没有性能开销。当Box
离开作用域时,会调用析构函数来销毁所有内部对象并释放内存。
#pragma once
#include <string>
#include <iostream>
#include <memory>
template <typename T>
class box {
T* e;
friend std::ostream& operator<<(std::ostream& s, box<T>& c);
friend std::ostream& operator<<(std::ostream& s,const box<T>& c);
friend std::string& operator<<(std::string& s, box<T>* c) {
c == nullptr ? s += "null" : s << *c; return s;
};
friend std::string& operator<<(std::string& s,const box<T>* c) {
c == nullptr ? s += "null" : s << *c; return s;
};
friend std::string& operator<<(std::string& s, box<T>& c) {
c.e == nullptr ? s += "null" : s << c.e; return s;
};
friend std::string& operator<<(std::string& s,const box<T>& c) {
c.e == nullptr ? s += "null" : s << c.e; return s;
};
public:
box(): e(nullptr) {}
box(std::nullptr_t):e(nullptr) {}
box(T&& _): e(new T(_)) {}
~box() { if (e != nullptr)delete e, e = nullptr; }
void operator = (T s) { e = new T(s); }
T& operator() (){ return *e; }
const T& operator() ()const { return *e; }
const T* $() const { return e; }
};
template <typename T>
std::ostream& operator<<(std::ostream& s, box<T>& c) { return s << (c.e == nullptr ? "null" : *c.e); }
template <typename T>
std::ostream& operator<<(std::ostream& s,const box<T>& c) { return s << (c.e == nullptr ? "null" : *c.e); }
template<class T>
struct is_box: std::false_type {};
template<typename T>
struct is_box<box<T>>: std::true_type {};
template<typename T> struct box_pack {};
template<typename T> struct box_pack<box<T>> { using type = T; };
template<typename T> using box_pack_t = typename box_pack<T>::type;
//int main() {
// box<std::string> s;
// std::cout << std::boolalpha << s << std::endl;
// s = "dsg";
// std::cout << s;
//}
然后在实体类,例如我是这么用的
#include "box.hh"
#include <src/fuckJson.hpp>
static int RES_INIT = orm::InitializationOrm();
using namespace std; using namespace orm;
class Tab;
class Type;
Class(Tab)
uint32_t id;
bool ok;
text<15> name;
tm date;
vector<Type> types;
box<Type> type;
Tab(uint32_t a = 0, bool b = false, const char* c = "", tm d = now(), vector<Type> e = {}, box<Type> f = nullptr) :
id(a), ok(b), name(c), date(d), types(e), type(f) {}
FUCKJSON(Tab, id, ok, name, date, types, type)
Class(Type)
uint8_t id;
text<10> language;
double bigBlob;
vector<Tab> tabs;
box<Tab> tab;
Type(uint8_t a = 0, const char* b = "", double c = 0, vector<Tab> d = {}, box<Tab> e = nullptr) :
id(a), language(b), bigBlob(c), tabs(d), tab(e) {}
FUCKJSON(Type, id, language, bigBlob, tabs, tab)
这样做可以替代裸指针,并且,更容易写之后的实现方法。而不是让裸指针以组合的方式写到方法里面。