c/c++:efficient c++,跟踪实例

再看 efficient c++, 写一下笔记。

这是写第一章:跟踪实例。

主要讲一个类,用于跟中,有一个公共变量控制是否需要跟踪,跟踪什么这个看个人要求,通过怎么实现跟踪类能够达到消耗最低。

//初始版本
class Trace
{
public:
    Trace(const string &name);
    ~Trace();
    void debug(const string &msg);

    static bool traceIsActive;
private:
    string theFunctionName;
};

inline
Trace::Trace(const string &name):theFunctionName(name)
{
    if(traceIsActive)
    {
        cout<<"Enter function "<<name<<endl;
    }
}

 

 初始时类的构造如上。

 调用版本1

//调用版本1
int addOne(int x)
{
    string name = "addOne";
    Trace t(name);
    retur x+1;
}

 

 

构造函数的参数类型从 string 变为 char * 。

//构造函数2,调用版本2,
int addOne(int x)
{
    char *name ="addOne";
    Trace t(name);
    return x+1;
}

inline
Trace::Trace(const char* name):theFunctionName
{
    if(traceIsActive)
    {
        cout<<"Enter function "<<name<<endl;
    }
}

 

这样在 Trace(name) 时不需要创建一个 name 的字符串。

 

在需要跟踪的时候类才给自身的变量分配空间。

//构造函数3,需要修改class 中theFunctionName 的类型,
Trace::Trace(const char* name):theFunctionName(0)
{
    if(traceIsActive)
    {
        cout<<"Enter function "<<name<<endl;
        theFunctionName=new string(name);
    }
}

class Trace
{
private:
    string * theFuntionName;
}

inline
Trace::~Trace()
{
    if(traceIsActive)
    {
        delete theFunctionName;
    }
}

 

最后的版本的开销最小,具体数据就看书上的。

要点:

1.对象定义会触发隐形地执行构造函数和析构函数。

2.因为通过引用传递对象还是不能保证良好的性能,所以避免对象的复制的确有利于提高性能。但是如果我们不必一开始就创建和销毁该对象(与temp 相反)的话,这种方式将更有利于性能的提升。

3.不要把精力浪费在计算结果根部不会被使用的地方。(如上面当traceIsActive为FALSE时的第二个版本,该类都会为创建string 空间)

4.在完成同样的简单工作时,(简单工作!)char 指针有时比string 对象更有效率。

5.内联消除了常被使用的小函数调用所产生的函数开销。

posted @ 2012-07-14 14:20  A_zhu  阅读(461)  评论(0编辑  收藏  举报