栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++实现rust的Box

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++实现rust的Box

Box 是一个智能指针,指向在类型为T的堆上分配的数据。Box 允许将数据存储在堆而不是栈上。Box没有性能开销。当Box离开作用域时,会调用析构函数来销毁所有内部对象并释放内存。

#pragma once
#include 
#include 
#include 
template 
class box {
  T* e;
  friend std::ostream& operator<<(std::ostream& s, box& c);
  friend std::ostream& operator<<(std::ostream& s,const box& c);
  friend std::string& operator<<(std::string& s, box* c) {
	c == nullptr ? s += "null" : s << *c; return s;
  };
  friend std::string& operator<<(std::string& s,const box* c) {
	c == nullptr ? s += "null" : s << *c; return s;
  };
  friend std::string& operator<<(std::string& s, box& c) {
	c.e == nullptr ? s += "null" : s << c.e; return s;
  };
  friend std::string& operator<<(std::string& s,const box& 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 
std::ostream& operator<<(std::ostream& s, box& c) { return s << (c.e == nullptr ? "null" : *c.e); }
template 
std::ostream& operator<<(std::ostream& s,const box& c) { return s << (c.e == nullptr ? "null" : *c.e); }

template
struct is_box: std::false_type {};
template
struct is_box>: std::true_type {};
template struct box_pack {};
template struct box_pack> { using type = T; };
template using box_pack_t = typename box_pack::type;
//int main() {
//  box s;
//  std::cout << std::boolalpha << s << std::endl;
//  s = "dsg";
//  std::cout << s;
//}

然后在实体类,例如我是这么用的

#include "box.hh"
#include 
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 types;
box type;
Tab(uint32_t a = 0, bool b = false, const char* c = "", tm d = now(), vector e = {}, box 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 tabs;
box tab;
Type(uint8_t a = 0, const char* b = "", double c = 0, vector d = {}, box e = nullptr) :
  id(a), language(b), bigBlob(c), tabs(d), tab(e) {}
FUCKJSON(Type, id, language, bigBlob, tabs, tab)

这样做可以替代裸指针,并且,更容易写之后的实现方法。而不是让裸指针以组合的方式写到方法里面。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953721.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号