Thread: points and classes question

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    731

    points and classes question

    If my class contains a variable that is a pointer, will the data of the assigned variable (the data being assigned to the pointer) be stored in the pointer or just the address.

    If it is just the address than once the source data is deleted the pointer will no longer work?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yes. A pointer holds an address, so if you assign one pointer value to a pointer variable, only the address will be stored in the pointer. If you delete the original, the stored pointer will exhibit undefined behavior, meaning it could crash, it could work accidentally sometimes but not others, it could just give strange results, etc.

  3. #3
    Registered User
    Join Date
    Aug 2004
    Posts
    731
    So I should be careful were I use pointers and that, ok thanks.

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Yes. This is why pointers are not used as often in C++. If copying is simple and inexpensive, just store objects. If copying is expensive or not what the design calls for, use a smart pointer like shared_ptr.

    Also, if you do use plain pointers as a class variable, remember that only the adress is copied when your class is copied, so you often want to write the copy constructor and copy assignment operator to correctly copy the data. Objects and shared_ptr's are copied automatically.

  5. #5
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    If it is just the address than the source data is deleted the pointer will no longer work?
    It's not exactly clear what you are asking here, but if two pointers point to the same data, and you delete the data, then neither pointer will point to the data anymore. Technically, both pointers will still work in that they can be assigned the addresses of other data, but they won't work to get at the data you deleted.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  2. Classes and Threads
    By Halloko in forum Windows Programming
    Replies: 9
    Last Post: 10-23-2005, 05:27 AM
  3. two-dimensional dynamic array of pointers to classes
    By Timo002 in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 06:18 AM
  4. Replies: 2
    Last Post: 06-18-2004, 08:08 PM
  5. Classes and Derivation
    By phatslug in forum C++ Programming
    Replies: 4
    Last Post: 06-02-2002, 09:19 PM