温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++智能指针对程序文件大小有什么影响

发布时间:2021-08-25 20:42:03 来源:亿速云 阅读:115 作者:chen 栏目:编程语言

本篇内容介绍了“C++智能指针对程序文件大小有什么影响”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

  C++智能指针对程序文件大小的影响

  于是我想做一个实验,看智能指针会带来多大的文件体积开销。

  于是做了个对比实验:

  raw_ptr.cpp

  #include < iostream>

  #include < vector>

  using namespace std;

  class Child;

  class Parent {

  public:

  ~Parent();

  Child* newChild();

  void hello() {

  cout << "Parent::Hello" << endl;   }   private:   vector children_;   };   class Child {   public:   Child(Parent *p) : parent_(p) {}   void hello() {   cout << "Child::Hello" << endl;   parent_->hello();

  }

  private:

  Parent *parent_;

  };

  Child* Parent::newChild()

  {

  Child *child = new Child(this);

  children_.push_back(child);

  return child;

  }

  Parent::~Parent()

  {

  for (int i = 0; i < children_.size(); ++i)   delete children_[i];   children_.clear();   }   int main() {   Parent p;   Child *c = p.newChild();   c->hello();

  return 0;

  }

  smart_ptr.cpp

  #include < iostream>

  #include < vector>

  #include < memory>

  using namespace std;

  class Child;

  class Parent : public enable_shared_from_this {

  public:

  ~Parent();

  shared_ptr newChild();

  void hello() {

  cout << "Parent::Hello" << endl;   }   private:   vector > children_;

  };

  class Child {

  public:

  Child(weak_ptr p) : parent_(p) {}

  void hello() {

  cout << "Child::Hello" << endl;   shared_ptr sp_parent = parent_.lock();   sp_parent->hello();

  }

  private:

  weak_ptr parent_;

  };

  shared_ptr Parent::newChild()

  {

  shared_ptr child = make_shared(weak_from_this());

  children_.push_back(child);

  return child;

  }

  Parent::~Parent()

  {

  children_.clear();

  }

  int main() {

  shared_ptr p = make_shared();

  shared_ptr c = p->newChild();

  c->hello();

  return 0;

  }

  empty.cpp

  #include < iostream>

  int main()

  {

  std::cout << "hello" << std::endl;   return 0;   }   Makefile   all:   g++ -o raw_ptr raw_ptr.cpp -O2   g++ -o smart_ptr smart_ptr.cpp -O2   g++ -o empty empty.cpp -O2   strip raw_ptr   strip smart_ptr   strip empty   empty 是什么功能都没有,编译它是为了比较出,raw_ptr.cpp 中应用程序代码所占有空间。   将 raw_ptr 与 smart_ptr 都减去 empty 的大小:   raw_ptr 4192B   smart_ptr 8360B   而 smart_ptr 比 raw_ptr 多出 4168B,这多出来的就是使用智能指针的开销。   

目前来看,智能指针额外占用了一倍的程序空间。它们之间的关系是呈倍数增长,还是别的一个关系?   

那么引入智能指针是哪些地方的开销呢?

  大概有:

  类模板 shared_ptr, weak_ptr 为每个类型生成的类。

  代码逻辑中对智能指针的操作。

  第一项是可预算的,有多少个类,其占用的空间是可预知的。而第二项,是很不好把控,对指针对象访问越多越占空间。

  总结:

  使用智能指针的代价会使程序的体积多出一半。

“C++智能指针对程序文件大小有什么影响”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI