1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 001 Figuring in C/C++

001 Figuring in C/C++

时间:2022-06-30 16:04:48

相关推荐

001 Figuring in C/C++

1. forward declaration

// Functionvoid fun(int);

在此之后的代码可以引用fun,而fun的定义必须在某个地方提供。

// Variables may have only forward declaration and lack definition// During compilation time these are initialized by language specific rulesint foo; //foo might be defined somewhere in this fileextern int bar; //bar must be defined in some other file

在其他文件中定义的变量必须用extern进行前置声明。

// Typeclass A;struct B;A fun(A arg); // PassA* pa; // Pass, but can't (*pa).member or pa->somefun();A& ra = *pa; // Pass, but cant't ra; ra.member; ra.somefun();A a; // Error

在知道这个类型的完整定义之前,只能用于作为类型的声明,而不能实际的定义变量。

2. POD type 包括以下类型

扩展:http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

3. 初始化列表的意义

列表先于构造函数调用,并调用父类,成员的构造函数进行初始化。(若在列表初始化成员,则无需在{}中再次的赋值初始化,有一定的效能提升)

初始化列表顺序:父类,成员声明的顺序。

4. Return Value Optimization

struct L{int la;L(){printf("Default Ctor L %p:%d\n", this, la);}L(int a):la(a){ printf("User Ctor L %p:%d\n", this, la);}L(const L& ot){if( this != (&ot)){(*this) = ot;};printf("Copy L %p from %p %d\n", this, &ot, la);}L& operator=(const L&ot){la=ot.la; printf("=L %p from %p %d\n", this, &ot, la);return (*this);}~L(){printf("~L %p:%d\n", this, la);}};L fun(L arg){printf("funin\n");return L(arg);// or // L tl = arg;// return tl;}int main(){fun(1);printf("funout\n");return 0;}// one possible output in gcc 3.4.4/*User Ctor L 0xbff89990:1 // 参数构造funin=L 0xbff899a0 from 0xbff89990 1Copy L 0xbff899a0 from 0xbff89990 1 // 函数内局部对象拷贝构造~L 0xbff899a0:1 // 函数内局部对象析构~L 0xbff89990:1 // 参数析构funout*/

按照道理,这里应该有三个对象的析构才对:函数内局部对象,返回于函数调用栈的临时对象,函数的参数。

再来看下面的输出

L object = fun(1);printf("funout\n");return 0;// one possible output in gcc 3.4.4/*User Ctor L 0xbfe0b3d0:1 // 参数构造funin=L 0xbfe0b3e0 from 0xbfe0b3d0 1Copy L 0xbfe0b3e0 from 0xbfe0b3d0 1 // 函数内局部对象拷贝构造~L 0xbfe0b3d0:1 // 参数析构funout~L 0xbfe0b3e0:1 // object析构*/

按照道理,这里应该有四个对象的析构才对:函数内局部对象,返回于函数调用栈的临时对象,函数的参数,对象object。

RVO是一项编译器相关的代码优化技术,在这里我们可以发现在对object进行拷贝构造时也优化了。

版权声明:本文为博主原创文章,未经博主允许。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。