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*'"
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.
two things,
static_cast
- 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...
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.
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
.
精彩评论