内联函数-及CONST的使用-函数返回引用的规则和注意事项






#include <iostream> #include <string> #include <vector> using namespace std; inline void swap(int *a, int *b){ //内联函数有一下几个优点: int temp = *a; //可以看做更高级的宏函数 *a = *b; //编译期间被内联展开 *b = temp; //没有函数调用的开销 } //编译器可以检测出内联函数的错误 int main(int argc, const char *argv[]) { int a = 10; int b = 9; swap(&a, &b); return 0; }
//内联函数:
  //用一种更高级的方式在程序中替换(目前为止,我们的能力还不足以探讨这个问题)
  //1. 可以看做更高级的的宏函数
  //2、 编译期间被内联展开
  //3. 没用函数调用开销
  //4. 编译器可以检测出内联函数的错误
 

 

 

1.宏函数:

a)      在预处理期间被文本展开

b)     没有函数调用的开销

c)      缺点是如果不被调用,编译器就无法为其检查错误。(编译器根本找不到这段代码,因为该代码预处理期间就消失了)

2.内联函数:

a)      可以看做高级的宏函数。

b)     编译期间被内联展开。

c)      没有函数调用开销。

d)     内联函数需要编译器检查语法合法。

 

与宏函数(其实它不是一个函数,只是我们这么称呼它)相比

 

  宏函数在编译时无法发现逻辑错误,只有在调用的时候才能发现其中的错误

 

2.const 的使用规则和注意事项

#include <iostream>
#include <string>
#include <vector>
using namespace std;

//函数返回值为value
string test()      //返回值为 string其实是一个值拷贝,将test函数中的s复制一个备份返回给调用者
{                            //这种返回方法其实是一种十分大的开销
    string s("hello");       //在类的使用上简易改成返回引用,这是我们使用引用的初衷
    return s;
}


int main(int argc, const char *argv[])
{
    string s = test(); 
    cout << s << endl;
    return 0;
}

 3.函数返回引用的方法

#include <iostream>
#include <string>
#include <vector>
using namespace std;

//返回值也可以是引用
const string &isShort(const string &s1, const string &s2)  //注意传入和传出都是引用
{
    return (s1.size() < s2.size()) ? s1 : s2;   //传出应当注意的是不可以将函数内部定义的局部变量当做一个引用传出
}                                               //因为在该函数的调用结束后,局部变量内存被释放,
                                                //其内存将成为非法内存(相对该进程而言)
                                               //如果在该进程别处对该地址引用或者指针解引用将造成访问越界
int main(int argc, const char *argv[])
{
    cout << isShort("hello", "foo") << endl; 
    return 0;
}

 

局部变量返回引用时:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

string &test()          //在这个例子中,我们看到一个string类型变量的值是"hello"
{                       //但是我们把它的值当做引用返回了
    string s("hello");   //实际上在return s;这句结束后, 变量s已经被释放
    return s;             //返回的引用已经不可用
}


int main(int argc, const char *argv[])
{
    string s = test(); 
    cout << s << endl;
    return 0;
}

 局部变量返回指针时:

 

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int *test()             //与上例同理
{
    int i;
    return &i;     //此句结束后,变量i被释放, 返回的int* 指向的是非法区域。
}

int main(int argc, const char *argv[])
{
    
    return 0;
}

 

 

当我们需要把引用当做传出参数时,必须确定它不是局部的变量,否则它的引用和指针不可用。

所以我们规定:禁止将局部变量的指针和引用, 当做引用返回

 

4.const 的使用

 

#include <iostream>
#include <string>
#include <vector>
using namespace std;

void print(const string &s)     //当我们写一个函数其实它对输入的引用  其实只进行读操作
{                                //我们必须在参数输入上加上const,因为我们并不期望 变量S被改变
     cout << s << endl;          //在代码书写上应该保持这种风格
}

void print2(const vector<int> &vec)
{
    cout << s << endl;
}


int main(int argc, const char *argv[])
{
    
    return 0;
}

 

posted @ 2014-09-17 16:32  tilly_chang  阅读(234)  评论(0编辑  收藏  举报