本篇内容介绍了“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 为每个类型生成的类。
代码逻辑中对智能指针的操作。
第一项是可预算的,有多少个类,其占用的空间是可预知的。而第二项,是很不好把控,对指针对象访问越多越占空间。
总结:
使用智能指针的代价会使程序的体积多出一半。
免责声明:本站发布的内容(图片、视频和文字)以原创、来自本网站内容采集于网络互联网转载等其它媒体和分享为主,内容观点不代表本网站立场,如侵犯了原作者的版权,请告知一经查实,将立刻删除涉嫌侵权内容,联系我们QQ:712375056,同时欢迎投稿传递力量。
Copyright © 2009-2022 56dr.com. All Rights Reserved. 特网科技 特网云 版权所有 特网科技 粤ICP备16109289号
域名注册服务机构:阿里云计算有限公司(万网) 域名服务机构:烟台帝思普网络科技有限公司(DNSPod) CDN服务:阿里云计算有限公司 百度云 中国互联网举报中心 增值电信业务经营许可证B2
建议您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流浏览器浏览本网站