C++ 面向对象高级编程 (上) week 2 (Boolan)

课程目标

  • 以良好的方式编写C++ class
    (Object Based: 面对的是单一class的设计)
    • class without pointer members -- Complex (week 1)
    • class with pointer members -- String (week 2)
  • 学习Classes之间的关系
    (Object Oriented: 面对的是多重classes的设计, classes和classes之间的关系)
    • 继承 (inheritance)
    • 复合 (composition)
    • 委托 (delegation)

Big Three, 三个特殊函数

class String {
 public:
  String(const char* cstr = 0);
  String(const String &str);             // 1. copy constructor
  String& operator=(const String &str);  // 2. copy assignment
  ~String();                             // 3. destructor
  char* get_c_str() const { return m_data; }
 private:
  char *m_data;
};

关于copy control (Big Three + move constructor / assignment) (摘自C++ Primer):

When we define a class, we specify—explicitly or implicitly—what happens when objects of that class type are copied, moved, assigned, and destroyed. A class controls these operations by defining five special member functions: copy constructor, copy-assignment operator, move constructor, move-assignment operator, and destructor. The copy and move constructors define what happens when an object is initialized from another object of the same type. The copy- and move-assignment operators define what happens when we assign an object of a class type to another object of that same class type. The destructor defines what happens when an object of the type ceases to exist. Collectively, we’ll refer to these operations as copy control.

Constructor 和 Destructor (构造函数和析构函数)

inline
String::String(const char *cstr = 0)
{
  if (cstr) {
    m_data = new char [strlen(cstr) + 1];
    strcpy(m_data, cstr); 
  } else {
    m_data = new char [1];
    *m_data = '\0';
  }
}

inline
String::~String()
{
  delete[] m_data;
}

析构函数的定义(摘自C++ Primer):

The destructor operates inversely to the constructors: Constructors initialize the nonstatic data members of an object and may do other work; destructors do whatever work is needed to free the resources used by an object and destroy the
nonstatic data members of the object.
The destructor is a member function with the name of the class prefixed by a tilde (~). It has no return value and takes no parameters. Because it takes no parameters, it cannot be overloaded. There is always only one destructor for a given class.

析构函数 何时被调用? (摘自C++ Primer):

The destructor is used automatically whenever an object of its type is destroyed:

  • Variables are destroyed when they go out of scope.
  • Members of an object are destroyed when the object of which they are a part is destroyed.
  • Elements in a container—whether a library container or an array—are destroyed when the container is destroyed.
  • Dynamically allocated objects are destroyed when the delete operator is applied to a pointer to the object.
  • Temporary objects are destroyed at the end of the full expression in which the temporary was created.

Because destructors are run automatically, our programs can allocate resources and (usually) not worry about when those resources are released.

Copy Constructor (拷贝构造函数)

inline
String::String(const String &str) // deep copy
{
  m_data = new char [strlen(str.m_data) + 1];
  strcpy(m_data, str.m_data);
}

拷贝构造函数的定义 (摘自C++ Primer):

A constructor is the copy constructor if its first parameter is a reference to the class type and any additional parameters have default values

拷贝构造函数 何时被调用? (摘自C++ Primer):

Copy initialization ordinarily uses the copy constructor (or the move constructor), and it happens when we

  • Define variables using an =;
  • Pass an object as an argument to a parameter of nonreference type;
  • Return an object from a function that has a nonreference return type;
  • Brace initialize the elements in an array or the members of an aggregate class;
  • Some class types also use copy initialization for the objects they allocate.

Copy Assignment Operator (拷贝赋值函数)

inline
String& String::operator=(const String &str)
{
  if (this == &str)  // self assignment
    return *this;
  delete [] m_data;
  m_data = new char [strlen(str.m_data) + 1];
  strcpy(m_data, str.m_data);
  return *this;
}

关于 operator overloading 和 copy assignment (摘自C++ Primer):

Overloaded operators are functions that have the name operator followed by the symbol for the operator being defined. Hence, the assignment operator is a function named operator=. Like any other function, an operator function has a return type and a parameter list.
The parameters in an overloaded operator represent the operands of the operator. Some operators, assignment among them, must be defined as member functions. When an operator is a member function, the left-hand operand is bound to the implicit this parameter. The right-hand operand in a binary operator, such as assignment, is passed as an explicit parameter.
The copy-assignment operator takes an argument of the same type as the class. To be consistent with assignment for the built-in types, assignment operators usually return a reference to their left-hand operand. It is also worth noting that the library generally requires that types stored in a container have assignment operators that return a reference to the left-hand operand.

何时定义 Big Three (The Rule of Three)

规则一: Classes That Need Destructors Need Copy and Assignment (摘自 C++ Primer):

One rule of thumb to use when you decide whether a class needs to define its own versions of the copy-control members is to decide first whether the class needs a destructor. Often, the need for a destructor is more obvious than the need for the copy constructor or assignment operator. If the class needs a destructor, it almost surely needs a copy constructor and copy-assignment operator as well.

规则二: Classes That Need Copy Need Assignment, and Vice Versa (摘自 C++ Primer):

Although many classes need to define all of (or none of) the copy-control members, some classes have work that needs to be done to copy or assign objects but has no need for the destructor. As an example, consider a class that gives each object its own, unique serial number. Such a class would need a copy constructor to generate a new, distinct serial number for the object being created. That constructor would copy all the other data members from the given object. This class would also need its own copy-assignment operator to avoid assigning to the serial number of the left-hand object. However, this class would have no need for a destructor.

Stack 和 Heap (栈和堆)

摘自C++ Primer:

Stack memory is used for nonstatic objects defined inside functions. Objects allocated in static or stack memory are
automatically created and destroyed by the compiler. Stack objects exist only while the block in which they are defined is executing; static objects are allocated before they are used, and they are destroyed when the program ends.
In addition to static or stack memory, every program also has a pool of memory that it can use. This memory is referred to as the free store or heap. Programs use the heap for objects that they dynamically allocate—that is, for objects that the program allocates at run time. The program controls the lifetime of dynamic objects; our code must explicitly destroy such objects when they are no longer needed.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,053评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,527评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,779评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,685评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,699评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,609评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,989评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,654评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,890评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,634评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,716评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,394评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,976评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,950评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,191评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,849评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,458评论 2 342

推荐阅读更多精彩内容