Thread: iterator to dereferencing to referencing again

  1. #1
    Registered User
    Join Date
    Oct 2005

    iterator to dereferencing to referencing again

    I vaguely remember reading somewhere that this was bad practice, but had to do it just to get around the compiler error:

    typedef stl_container<type> A;
    typedef different_container<type*> B;
    A a;
    B b;
    for(A::iterator it = a.begin(); it != a.end(); it++)
        b.insert(&(*it)); //dereference, then apply addressof operator again
    Let me emphasize that there is no way for me at the moment to get around this. I need to work on the original object later on, and not a copy. That's why I need to pass around a reference.

    What's the recommended way of doing this? And why is my kludge(?)workaround(?) discouraged?

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    It depends on what stl_container actually is. There are rules about address invalidation for the various containers. A list's entries are invalidated only when they're deleted. A vector's entries are invalidated if something is inserted/erased before their own position, or if the vector has to reallocate. I can't remember the deque rules, but they're harsh. The set and map rules are like list's.
    It's fine to hold pointers to objects in a container that doesn't invalidate. It's dangerous to hold pointers to objects in a container that does. If you know the container won't change during the lifetime of the container holding the pointers, though, you can do that, too.
    All the buzzt!

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    Registered User
    Join Date
    Jan 2005
    If the pointers might be invalidated, you can hold something else inside both A and B. For example, you could use a shared_ptr<type> inside both A and B. Then, both references should always be valid as long as you are using them.

  4. #4
    Registered User
    Join Date
    Oct 2005
    Well, I guess I lucked onto the correct solution then. The A container is a list, and the B container is a vector. Thanks for the help.

    And I'll keep the shared_ptr in mind when I have to use vectors or similar.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structures, Pointer Elements, and Dereferencing
    By cyreon in forum C Programming
    Replies: 3
    Last Post: 05-22-2009, 11:05 AM
  2. Replies: 0
    Last Post: 03-20-2008, 07:59 AM
  3. dereferencing void pointer
    By nkhambal in forum C Programming
    Replies: 4
    Last Post: 04-25-2005, 02:47 AM
  4. Glib and file manipulation
    By unixOZ in forum Linux Programming
    Replies: 1
    Last Post: 03-22-2004, 09:39 PM
  5. Problem in table referencing
    By elquex in forum C++ Programming
    Replies: 5
    Last Post: 03-26-2003, 03:00 AM