# CPPTest **Repository Path**: asdfgzxcvb/CPPTest ## Basic Information - **Project Name**: CPPTest - **Description**: 学习探究C++知识 - **Primary Language**: C++ - **License**: MulanPSL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2020-12-13 - **Last Updated**: 2023-03-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: Cpp ## README # CPPTest ## 在构造函数中使用new时应注意的事项 - 如果在构造函数使用`new`来初始化指针成员,则应该在析构函数中使用`delete`。 - `new`和`delete`必须兼容使用,`new`和`delete`互相对应,`new[]`和`delete[]`互相对应。 - 如果有多个构造函数,则必须以相同的方式使用`new`,要么都带中括号,要么都不带。应该析构函数只有一个,所有的构造函数都必须和析构函数兼容。 - 必须定义一个复制构造函数,通过深度复制一个对象初始化另一个对象,内容一般如下: ```c++ StringBad::StringBad(const StringBad & st) { num_strings++; // handle static member update if necessary len = st.len; // same length as copied string str = new char[len + 1]; // alloc apce strcpy_s(str, len + 1, st.str); // copy string to new location } ``` - 必须定义一个赋值运算符函数,通过深度复制一个对象初始化另一个对象,内容一般如下: ```c++ StringBad & StringBad::operator=(const StringBad & st) { if (this == &st) { // object assigned to itself return *this; // all done } delete[] str; // free old string space len = st.len; // same length as copied string str = new char[len + 1]; // alloc apce strcpy_s(str, len + 1, st.str); // copy string to new location return *this; // return reference to invoking object } ``` ## 移动语义和右值引用 先看看C++11之前的复制过程。假设有代码如下: ```c++ vector vstr;; // build up a vector of 20000 strings, each of 1000 characters vector vstr_copy1(vstr); // make vstr_copy1 a copy of vstr ``` `vector`和`string`类都是使用动态内存分配,和`StringBad`类似,因此它们必须定义使用某种`new`版本的复制构造函数。明显全部复制是妥当的,但是可能会浪费。比如,如下代码: ```c++ vector allcaps(const vector &vs) { vector temp; // code that stores an all-uppercase version of vs in temp return temp; } ``` 接下来,有如下使用方式: ```c++ vector vstr; // build up a vector of 20000 strings, each of 1000 characters vector vstr_copy1(vstr); // oop #1 vector vstr_copy2(allcaps(vstr); // oop #2 ``` `oop #1`和`oop #2` 最终的结果是把`vstr`拷贝到`vstr_copy#`中,但是在`oop #2`存在浪费。 移动语句:避免移动原始数据,仅仅修改记录。 此处仅仅展示下,移动复制运算符代码, ```c++ StringBad & StringBad::operator=(StringBad&& st) // move assignment { if (this == &st) { // object assigned to itself return *this; // all done } delete[] str; // free old string space len = st.len; // same length as copied string str = st.str; // modify the pointer to this st.len = 0; // reset old st.str = nullptr; // reset old return *this; // return reference to invoking object } ```