Link to home
Start Free TrialLog in
Avatar of HillRatIn4433
HillRatIn4433

asked on

How to use auto_ptr with char*

I'm trying to use the auto_ptr but I can't figure out how to get it to work with char*

Can some post an example
Avatar of thienpnguyen
thienpnguyen

auto_ptr is not designed to use with array. Note that, the destructor of auto_ptr
will delete  the  pointer to "an object or an primary type : char, int ..." not array.

    ~auto_ptr()
     {
           if (_Owns)
                delete _Ptr;  

          // note : syntax for deleting  array  ==> delete  [ ] _Ptrt
     }

Therefore, if you use  auto_ptr with array , you will have trouble.

For example
   
          main()
         {
                char *p = new char[200] ;
                auto_ptr<char>  X(  p );              
         }

At the time the program finished, destructor of X wil do
             delete _Ptr;      // _Ptr == p

however, what you expect  is    
            delete [ ] _Ptr
         
In conclusion, you can not use auto_ptr with array. If you want, you need to write
auto_array_ptr .

More information : http://gcc.gnu.org/onlinedocs/libstdc++/20_util/howto.html#1



ASKER CERTIFIED SOLUTION
Avatar of thienpnguyen
thienpnguyen

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>how to get it to work with char*
Well, if you're looking for a safe way of handling strings, why not use the std::string?

>>Can some post an example

#include <iostream>
#include <string>

int main()
{
  std::string   strExample;
  strExample = "Hello World!";
  std::cout << strExample << std::endl;
}
Avatar of HillRatIn4433

ASKER

Thanks
IainHere,
Thanks, but I'm already familiar with string.
Not that you have to answer, but what are you planning to do with this array of chars?  If it's not a string, why not use a std::vector<char>?  
I'm only asking because I can't think of a circumstance where I'd rather wrap an array of chars in an auto_array_ptr than use something else.
IainHere ,

Here is a  stituation.  Assume we use  char *getString( ... )  of 3rd party library.  
The function requires us to delete return value after using it.

I mean
 
     char *p = getString(...);

    // access p .....

    // release memory as getString require
    delete [] p;

If we have auto_array_ptr, we can do


    auto_array_ptr<char> p (  getString(...)  );


Fair Nuf :-)