简体   繁体   English

在 std::set (c++) 中获取指向 object 的指针

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

I have a std set S. S contains a few instances of MyType.我有一个标准集 S。S 包含几个 MyType 实例。 Is this the best way to get a pointer to an instance of MyType in S?这是在 S 中获取指向 MyType 实例的最佳方法吗?

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.编辑:我确实在上述行之前检查了 find 到 S.end() 的结果。

Edit : Removing the cast causes the following compile-time error: "Invalid conversion from 'const MyType*' to 'MyType*'"编辑:删除强制转换会导致以下编译时错误:“从 'const MyType*' 到 'MyType*' 的无效转换”

You should not take a mutable reference or pointer to an element in a set .不应将可变引用或指针指向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.编译时错误的存在是有充分理由的,此外,您的代码展示了一个很好的例子,说明了为什么 C 风格的强制转换不好——因为它们可以抛弃 const,而其他回答者都没有注意到,而如果你曾经被迫使用const_cast ,每个人都会注意到那有多糟糕。

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.但是,如果您采用有效的const MyType* ,那么强制转换将是多余的,并且&*iterator是 go 的一个非常好的方法。

two things,两件事情,

  1. static_cast
  2. You should really check that the object exists in the set before grabbing the pointer.在抓取指针之前,您应该真正检查集合中是否存在 object。

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...编辑:哎呀, static_cast也是多余的......习惯,每当我看到 C 风格的演员......

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?这是在 S 中获取指向 MyType 实例的最佳方法吗?

No. You don't need the cast.不,你不需要演员表。 And if you did, it shouldn't be a C cast, it should be a const_cast .如果你这样做了,它不应该是 C 演员,它应该是const_cast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM