menu

hjk41的日志

Avatar

Effective C++ Note 22: Prefer pass-by-reference to pass-by-value

1. efficiency
If you pass an object by value, then inside the function, a copy of the object will be created, which may be rather costly.

class Base{
public:
    Base();
    virtual ~Base();
    virtual display();
};

class Derived:public Base{
public:
    Derived();
    virtual ~Derived();
    virtual display();
private:
    Object a;
    Object b;
};

void f(Derived d){};

Derived d;
f(d);


A call to f() will invoke the constructor of Base, Derived once and the constructor of Object twice. Though compilers can eliminate some of the calls in some cases, it is better we do it ourselves. By passing the argument by value, we can be sure no additional constructors be called.

2. dynamic binding

void f2(Base b){
    b.display;
}

Derived d;
f2(d);


In this case, Base::display() will be called instead of Derived::display(). So if we want Derived::display() to be called, we should define f2() as void f2(Base & b).

评论已关闭