Item 20: Prefer pass-by-reference-to-const to pass-by-value

  1. 1. Part 4: Designs and Declarations
  2. 2. Things to remember
  3. 3. Key words
  4. 4. Copy-On-Write (COW):
    1. 4.1. Code

This article is one of <Effective C++> reading notes.

Part 4: Designs and Declarations

Item 20: Prefer pass-by-reference-to-const to pass-by-value.


Things to remember

  • Prefer pass-by-value-to-const over pass-by-value. It’s typically more efficient and it avoids the slicing problem.
  • The rule doesn’t apply to build-in types and STL iterator and function object types. For them, pass by value is usually appropriate.
  • 对于正常的 C++ 程序,传值的地方传 const 引用总是没错的。对象复制不仅成本太高,正确实现对象复制也不是件容易的事。如果想把对象置入一个容器,最好是使用它的引用。

Key words

Copy-On-Write (COW):

copy-on-write is the name give to the process of identifying when a task attempts to make a change to shared information, creating a separate(private) copy of that information for the task and redirecting the task to making changes to the private copy to prevent its changes from becoming visible to all other tasks.

Slicing Problem

“Slicing” is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is “sliced” away.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include "stdafx.h"
#include <iostream>
#include <string>
using std::string;
class Person {
public:
truePerson(string name, string address): name(name), address(address) { }
private:
truestring name;
truestring address;
};
class Student : public Person {
public:
trueStudent(string name, string address, string schoolName, string schoolAddress) \
truetrue: Person(name, address), schoolName(schoolName), schoolAddress(schoolAddress) { }
private:
truestring schoolName;
truestring schoolAddress;
};
bool validateStudent(Student s)
{
truereturn true; // test
}
bool validateStudent2(const Student& s)
{
truereturn true;
}
int main()
{
trueStudent plato("plato", "Athens", "Socrates", "Athens");
true// the overall cost of passing a Student by value is six constructors
true// and six destructors!
truebool platoIsOK = validateStudent(plato);
truesystem("pause");
truereturn 0;
}