现在的位置: 首页 > 编程语言 > 正文

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

2020年01月15日 编程语言 ⁄ 共 510字 ⁄ 字号 评论关闭

  引入了智能指针可以解决了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 为每个类型生成的类。

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

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

  总结:

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

抱歉!评论已关闭.