给定代码:
#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
}
指针可以从另一个函数中释放吗?这是我在这里想了解的主要内容。
最佳答案
您不应该手动调用析构函数 - 当 s
在最后的 '}' 处超出范围时调用它
断言失败意味着称为 assert(somecondition)
的东西和 somecondition 是假的。这是一种用于验证您的假设的技术 - 如果您的代码取决于某些特定条件为真,并且该条件确实应该为真,除非您有错误,然后您插入一个断言。
然后您可以选择在启用断言的情况下进行编译 - 这意味着如果您的假设是错误的,您将得到这样的错误。对于发布版本,您通常会禁用断言 - 不会为断言语句生成任何代码,也不会产生额外的运行时成本。
有些情况下手动调用析构函数是正确的 - 在您了解并使用“placement new”之前您不需要它。
关于c++ - 从另一个函数释放指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5458552/