开发者

Freeing a pointer from another function

开发者 https://www.devze.com 2023-02-20 10:58 出处:网络
Given the code: #include<iostream> using namespace std; class String { char *pstr; unsigned size; public:

Given the code:

#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();
}

Output:

    String is - Hello World - of size 11
    Hello World
    In Dtor
----Debug Assertion Failure----
    In Dtor

Why does the Destructor get called again? When i have invoked the destructor?

And what is an Assertion Failure?

Also is this code Valid?

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
}

Can the pointer be freed from another function? This 开发者_StackOverflowis the main thing i am trying to understand here.


You should not invoke the destructor manually - it's invoked when s goes out of scope at the final '}'

An assertion failure means that something called assert(somecondition) and somecondition was false. It's a technique used to validate your assumptions - if your code depends on some specific condition being true, and that condition really should be true unless you have a bug, then you insert an assert.

You can then choose to compile with assertions enabled - this means that you'll get such an error if your assumption was wrong. For a release build, you often disable assertions - no code is generated for the assert statement, and there's no extra runtime cost.

There are cases when it's correct to manually invoke the destructor - You won't need this until you learn about and use "placement new".


In addition to what Erik has already said:

Your code would still remain prone to double deletion after you remove manual destructor call: you have to either disable copy constructor/assignment operator, or implement them correctly (you'll need reference counting if you insist on owning heap-allocated memory).

0

精彩评论

暂无评论...
验证码 换一张
取 消