CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6

Thread: auto_ptr

  1. #1
    Join Date
    Apr 2004
    Posts
    5

    Question auto_ptr

    Hi,
    I've a basic question regarding auto_ptr

    assume this
    auto_ptr<T> pt( new T(1) );

    now how do i validate pt before using pt.get()i.e
    how can I make sure that pt has been allocated....

    is there any way to validate, as iam using this for the first time.Kindly someone clarify


    Thanx in advance

  2. #2
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652
    Actually, you already answered your own question....'get' will return 0 in case of a failure. Besides that...'new' is supposed to throw a 'bad_alloc' exception in case of a failure...

  3. #3
    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    762
    Adding onto his question, do you know of any lists that basically say what can throw what excepts and when it happens? It would be nice to trap specific errors for debugging.

  4. #4
    Join Date
    Apr 2004
    Posts
    5

    Question

    Thanx...
    but I still have a doubt, i.e
    in case of normal allocation using new
    for eg

    a = new b;

    we can check
    if( a!= NULL)
    {}

    similarly without using get can we check the same in the case of auto_ptr

  5. #5
    Join Date
    Jun 2003
    Location
    Gjøvik, Norway
    Posts
    204
    Firstly... Like Andreas said... new should not return NULL according to the standard. If allocation fails, it should throw a std::bad_alloc exception, and therefore you should not need to check for NULL. (VC++ does however return NULL if allocation fails, because it is not conforming to the standard at that point. If that's your compiler, the check is valid.)

    Secondly... Why can't you use get() to check the validity?
    Code:
    if(!your_auto_ptr.get())
    	{
    	// something went wrong!
    	}

  6. #6
    Join Date
    Apr 1999
    Location
    Altrincham, England
    Posts
    4,470
    Just as a quick point in partial answer to one question raised earlier about what exceptions can be thrown: std::auto_ptr has a nothrow guarantee on all its member functions.

    So
    Code:
    std::auto_ptr<T> p(new T);
    the "new" might throw, but the constructor won't.
    Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
    --
    Sutter and Alexandrescu, C++ Coding Standards

    Programs must be written for people to read, and only incidentally for machines to execute.

    --
    Harold Abelson and Gerald Jay Sussman

    The cheapest, fastest and most reliable components of a computer system are those that aren't there.
    -- Gordon Bell


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured