C++学习笔记02之三大函数和栈,堆与内存管理
2016-09-17 14:31
447 查看
一、三大函数
因为Class的另一种分类:Class with pointer member(s):string 字符串
在string.h里便有三个特殊函数(The Big Three):拷贝构造函数、拷贝赋值函数(包括运算符=重载)、析构函数。
String-test.cpp:
int main() { String s1(); String s2("hello"); String s3(s1); // s3被创建,故对应拷贝构造函数 cout << s3 <<endl; s3 = s2; // 对应拷贝赋值函数 cout << s3 << endl; }
相关函数的声明与实现:
class String { public: String(const char* cstr = 0); // 构造函数 String(const String& str); // 拷贝构造函数 String& operator = (const String& str); // 拷贝赋值函数(包括运算符重载) ~String(); // 析构函数,dtor char* get_c_str() const { return m_data; } private: char* m_data; }; inline String::String(const char* cstr = 0) // 构造函数 { if (cstr) { m_data = new char[strlen(cstr) + 1]; // new表示动态内存分配,而字符串结尾有一个结束标志'\0',故加一 } else { // 未指定初值 m_data = new char[1]; *m_data = '\0'; } } inline String::~String() // 析构函数 { delete[] m_data; // delete释放掉new出来的内存,防止内存泄露 } // 浅拷贝(系统默认)和深拷贝 inline String::String(const String& str) // 拷贝构造函数 { m_data = new char[strlen(str.m_data) + 1]; strcpy(m_data, str.m_data); } inline String& String::operator = (const String& str) { if (this == &str) // 检测自我赋值 return *this; delete[] m_data; m_data = new char[strlen(str.m_data) + 1]; strcpy(m_data, str.m_data); return *this; }output函数:
#include <iostream.h> ostream& operator << (ostream& os, const String& str) { os << str.get_c_str(); return os 4000 ; } { String s1("hello "); cout << s1; }
二、栈,堆与内存管理
栈,堆创建对象新的方式:
1.stack objects
Complex c1(1, 2);
2.static local objects
static Complex c2(1, 2);
其生命在作用域(scope)结束之后依然存在,知道整个程序结束。
3.global objects
class Complex{ ... }; ... Complex c3(1, 2); int main() { ... }其作用域是整个程序。
4.heap objects
class Complex{ ... }; ... { Complex* p = new Complex; ... delete p; // 防止内存泄露 }解释:
new:先分配memory,再调用ctor
delete:先调用dtor,再释放memory
内存管理
array new 一定要搭配 array delete
相关文章推荐
- C++中虚析构函数的作用
- c++ 与 Java 之 红黑树 哈希表 辨析
- C++11中std::function的使用
- C++11中std::function的使用
- (十一)c52学习之旅-动态数码管
- C语言 获取字符串的方法
- OC语言基础
- glut 双缓冲动画 ---不用glutTimerFunc函数
- 【栈和队列】一个数组实现两个栈
- 【LeetCode-111】Minimum Depth of Binary Tree(C++)
- JNI技术---clojure 调用C++库的方法
- (十)c52学习之旅-定时器实验
- 【LeetCode-257】Binary Tree Paths(C++)
- 统计C/C++有效代码量
- (C语言版)猴子吃桃问题
- C++中static关键字
- C语言解题报告模板
- 剑指offer系列源码-八皇后问题 C语言
- C++11中rvalue references的使用
- C++11中rvalue references的使用