3、C++ 动态内存分配:
使用 "new" 和 "delete"
如下示例:文件: AllocNewTest.cpp
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class CCC
- {
- public:
- CCC(){cout<<"CCC()"<<endl;};
- ~CCC(){cout<<"~CCC()"<<endl;};
- CCC(int);
- CCC(int, double);
- int ii;
- double dd;
- };
- CCC::CCC(int _ii)
- : ii(_ii)
- {
- };
- CCC::CCC(int _ii, double _dd)
- : ii(_ii), dd(_dd)
- {
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- CCC *cc1 = new CCC(4, 5.5); // Pointer. Contructor called.
- CCC *cc2 = new CCC[5]; // Pointer to an array of objects.
- CCC &cc3 = *new CCC; // Reference
- CCC **c4 = new CCC * [5]; // Array of pointers to pointers
- cc1->ii = 5;
- cc2[3].ii = 6;
- cc3.ii = 7;
- c4[0] = new CCC(8);
- c4[1] = new CCC(9);
- cout << cc1->ii << endl;
- cout << cc2[3].ii << endl;
- cout << cc3.ii << endl;
- cout << c4[0]->ii << endl;
- cout << c4[1]->ii << endl;
- delete cc1;
- delete [] cc2;
- delete & cc3;
- delete [] c4[0]; // First delete pointer content
- delete [] c4[1];
- delete [] c4; // then delete array of pointers
- return 0;
- }
注意:
-
new CCC(3) 为integer 成员的单个对象分配的内存并且设置integer 成员成3.
-
new CCC[3] 创建三个对象,并没有初始化变量
结果如图:

图四
4、C 函数返回一个指针vs C++函数返回的是一个副本:
C 函数返回一个指针
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- char *fnConvert(int _ii)
- {
- char *str =(char*)malloc(10); /* Return 10 character string */
- if(str == NULL)
- fprintf(stderr,"Error: Memory allocation failed.\n");
- sprintf(str, "%d", _ii);
- return str;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- char *s1=fnConvert( 34567 );
- printf("%s\n", s1);
- free(s1);
- return 0;
- }
运行结果:

图五
C++ 函数返回的是一个副本:
- // memory.cpp : 定义控制台应用程序的入口点。
- //2011/10/13 by wallwind
- #include "stdafx.h"
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- string fnConvert(int _ii)
- {
- ostringstream ost;
- ost << _ii;
- return ost.str();
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- cout << fnConvert( 34567 ) << endl;
- return 0;
- }
运行结果

图六
注意:c++的STL string类的赋值构造函数是被用来返回一个值的副本,也就是当我们离开了函数的时候,变量 "ost",不在作用域了,但是所赋复制的内容是有效的。不要返回"return ost.str().c_str()" 作为他的指针,他是不在作用域的内一旦程序离开了函数,并且数据会丢失。
