Pointer and new Question

This is a discussion on Pointer and new Question within the C++ Programming forums, part of the General Programming Boards category; Hallo, What is the difference between: Code: someClass *ptr = new someClass; and Code: someClass temp; someClass *ptr = &temp; ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Location
    UK/Norway
    Posts
    485

    Pointer and new Question

    Hallo,

    What is the difference between:
    Code:
    someClass *ptr = new someClass;
    and
    Code:
    someClass temp;
    someClass *ptr = &temp;
    To me the last one looks a lot better, as I have heard the new is a slow command, and that when you use new you also need to have delete. But I am feeling that I am missing something here...

    Thanks

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    The first one points to allocated memory, the second one points to an automatic(?).
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    dra
    dra is offline
    Weak. dra's Avatar
    Join Date
    Apr 2005
    Posts
    166
    Quote Originally Posted by h3ro View Post
    Hallo,

    What is the difference between:
    Code:
    someClass *ptr = new someClass;
    and
    Code:
    someClass temp;
    someClass *ptr = &temp;
    To me the last one looks a lot better, as I have heard the new is a slow command, and that when you use new you also need to have delete. But I am feeling that I am missing something here...

    Thanks
    New dynamically allocates memory that won't be removed until delete is called on the pointer. What happens when temp goes out of scope? What will ptr point to then?

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,659
    A pointer is just a variable that holds an address. In the first, new allocates memory and returns a pointer to that new memory. The second assigns the address from a stack variable to the pointer.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

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