0

Is it possible to save a pointer to an object in a vector inside a loop?

For example:

rpc::session* session=NULL;

//Find Sessions with same UserID, Remove if > 1
for(std::vector<rpc::session>::iterator it = session_manager::sessions.begin(); it != session_manager::sessions.end();) {
  if(it->userid == userid){
    if(session == NULL) {
      *session = *it;
      ++it;
    } else {
      it = session_manager::sessions.erase(it);
    }
  } else {
    ++it;
  }
}

The code gets compiled but as soon as it reaches *session = *it, it crashes with a Access violation..

4 Answers 4

2

Because you're not assigning the address of your session to your session variable, and seeing your vector is storing session objects and not pointers, you need to assign the address of your variable to your pointer.

session = &(*it);

This assigns the address of what is in *it to session

Sign up to request clarification or add additional context in comments.

1 Comment

@LuchianGrigore haaha, I misread the intent of the code. Fixed
2

That's because you're attempting to dereference a NULL pointer. If you want to save a pointer to that object, you need to assign the pointer session itself - session = &(*it).

Comments

2

This is because you try to copy the contents of a session object into a nullptr. You either have to allocate memory and copy into that memory or copy the pointer into another location.

Please be aware, that taking the address of the element in the vector is no good solution in your case as a vector::erase() will move the elements in the vector, making a previously stored address invalid.

In your case it might still work, as you will store only the last session found in the vector. If you want to store all sessions with the correct user id you need to do something like

std::vector<rpc::session> result;
std::copy_if(session_manager::sessions.begin(), 
             session_manager::sessions.end(), 
             result.begin(), 
             [&](rpc::session s) -> bool 
             {
                 return s.userid == userid;
             }
             );

Comments

1

You can get a pointer to an element in a vector, but what you're doing with *session = *it; is not getting the pointer to the element but getting its value and trying to copy it to another rpc::session object that was never allocated. If you want the pointer to the rpc::session object in the vector, you should do

session = &(*it);

1 Comment

I need to learn to type faster... two similar answers got posted in the time I took to write mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.