auto pointer

This is a discussion on auto pointer within the C++ Programming forums, part of the General Programming Boards category; Hi, Is it possible to use auto pointer to point to an existing variable? I tried the following an get ...

  1. #1
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    452

    auto pointer

    Hi,
    Is it possible to use auto pointer to point to an existing variable?
    I tried the following an get segfault:
    Code:
      int c = 0;
      
      std::auto_ptr<int> a (&c);
    I know that I can use new to allocate memory for "a" then assign the value of "c" to a, but that doesn't mean that 'a' point to c:
    Code:
    std::auto_ptr<int> a ( new int(c));
    "All that we see or seem
    Is but a dream within a dream." - Poe

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,293
    Of course you'll get a segfault. It would be the same as writing:
    Code:
    delete &c;
    which is of course ridiculous. You can't delete something that was not allocated dynamically.

    The purpose of an auto_ptr is to delete something automatically without having to remember to do it yourself.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    -bleh-
    Join Date
    Aug 2010
    Location
    somewhere in this universe
    Posts
    452
    thanks iMalc for the answer.
    "All that we see or seem
    Is but a dream within a dream." - Poe

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to a function pointer
    By @nthony in forum C Programming
    Replies: 3
    Last Post: 05-30-2010, 05:13 PM
  2. Quick Pointer Question
    By gwarf420 in forum C Programming
    Replies: 15
    Last Post: 06-01-2008, 03:47 PM
  3. Replies: 1
    Last Post: 03-24-2008, 10:16 AM
  4. Direct3D problem
    By cboard_member in forum Game Programming
    Replies: 10
    Last Post: 04-09-2006, 03:36 AM
  5. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21