解放出來一個指針:從給定的代碼中的另一個功能
#include<iostream>
using namespace std;
class String
{
char *pstr;
unsigned size;
public:
String(){ pstr=0;size=0;}
String(const char *);
void show(){ cout << pstr << endl ; }
~String() { cout << "In Dtor" << endl; delete [] pstr; }
};
String::String(const char * cptr)
{
size = strlen (cptr) + 1;
cout << "String is - " << cptr << " - of size " << size - 1 << endl ;
pstr = new char [ size ] ;
for (int i = 0 ; i < size ; i++)
pstr[ i ] = cptr [ i ];
}
int main()
{
String s("Hello World");
s.show();
s.~String();
}
輸出:
String is - Hello World - of size 11
Hello World
In Dtor
----Debug Assertion Failure----
In Dtor
爲什麼析構函數再次調用?當我調用析構函數時?
什麼是斷言失敗?
也是代碼有效嗎?
char * ptr=0;
void fun()
{
const char * p = "Hello World";
int size = strlen(p)+ 1;
cout << size << endl;
ptr = (char *)malloc(size);
for (int i = 0 ; i < size ; i++)
ptr[ i ] = p [ i ];
cout << p << endl << ptr << endl ;
}
int main()
{
fun();
free (ptr); --> Note
}
指針可以從另一個函數中釋放嗎?這是我在這裏試圖理解的主要內容。
不要求顯式調用析構函數,您不使用免費商店。 – DumbCoder 2011-03-28 11:53:10
@DumbCoder:即使在使用堆時,也不要明確調用析構函數。你只能調用'delete'。 – Xeo 2011-03-28 11:58:10
@Acme:在你的編輯:是的,你可以,但那不屬於同一個問題。另外,我確信它之前已經回答了:在提問之前進行搜索! – Xeo 2011-03-28 12:01:11