MrDatabase
MrDatabase

Reputation: 44445

Get a pointer to an object in a std::set (c++)

I have a std set S. S contains a few instances of MyType. Is this the best way to get a pointer to an instance of MyType in S?

MyType *pointerToMyType = (MyType*)(&*S.find(anotherInstanceOfMyType));

The above code works. I'm just not sure if it's the best or safest way.

Edit: I do check the result of find to S.end() before the above line.

Edit: Removing the cast causes the following compile-time error: "Invalid conversion from 'const MyType*' to 'MyType*'"

Upvotes: 1

Views: 5249

Answers (4)

Johann Gerell
Johann Gerell

Reputation: 25581

Assuming that you know the element exists...

Is this the best way to get a pointer to an instance of MyType in S?

No. You don't need the cast. And if you did, it shouldn't be a C cast, it should be a const_cast.

Upvotes: 1

Puppy
Puppy

Reputation: 146910

You should not take a mutable reference or pointer to an element in a set. If you change it's properties, then you will invalidate the container's invariants, causing Undefined Behaviour. That compile-time error is there for a good reason, and furthermore, your code shows an excellent example of why C-style casts are bad- because they can cast away const, and none of the other answerers noticed, whereas if you had been forced to use a const_cast, everybody would have noticed how bad that was.

However, should you take a valid const MyType*, then the cast will be redundant, and &*iterator is a perfectly good way to go about it.

Upvotes: 4

Peter Alexander
Peter Alexander

Reputation: 54270

What you have is fine, although:

  • You should probably check that the iterator is valid before dereferencing it.
  • There is no need for the cast.

Upvotes: 1

Nim
Nim

Reputation: 33655

two things,

  1. static_cast
  2. You should really check that the object exists in the set before grabbing the pointer.

As to the approach, if you fleshed out what you are trying to do, there could be a better way...

EDIT: oops, the static_cast is redundant too... habit, whenever I see a C-style cast...

Upvotes: 1

Related Questions