Reputation: 44445
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
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
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
Reputation: 54270
What you have is fine, although:
Upvotes: 1
Reputation: 33655
two things,
static_cast
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