C++将指针作为参数传递给引用时进行指针转换
我很好奇,是:
bool State::operator<(const State* S)
{
return this->operator<(*dynamic_cast<const State *>(S));
}
完全相同:
bool State::operator<(const State* S)
{
return this->operator<(*(S));
}
作为参考,被调用的 this->operator<
是:
bool State::operator<(const State& S)
{
return this->reward < S.reward ? true : false;
}
哪个更“正确”并且类型安全/安全使用,或者,有吗有什么实际区别吗?
I'm curious, is:
bool State::operator<(const State* S)
{
return this->operator<(*dynamic_cast<const State *>(S));
}
exactly the same as:
bool State::operator<(const State* S)
{
return this->operator<(*(S));
}
For reference the this->operator<
being called is:
bool State::operator<(const State& S)
{
return this->reward < S.reward ? true : false;
}
Which one is more "correct" and type safe / secure to use or, is there any actual difference ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,第一个将指针强制转换为自身,这实际上并没有执行任何操作,然后调用 const State* 重载,这会导致无限循环。在需要在运行时向下转换之前,您不需要
dynamic_cast
— 这里没有向下转换,因此这是唯一要做的事情。
No, the first one casts the pointer to itself, which doesn't really do anything, and then calls
const State*
overload, which results in an infinite loop. You don't needdynamic_cast
until you need to downcast at runtime — there is no downcasting here, sois the only thing to do.
假设您有一个拼写错误,并且您打算将以下内容进行比较:
...与此:
...其中 s 具有编译时类型
const State *
,则根本没有区别。可以想象,如果您的编译器没有注意到它们是编译时等效的,则前者可能会稍微慢一些。
我会避免前者,因为任何读它的人都会想知道你在想什么。
Assuming you have a typo and you mean to compare this:
...to this:
...where s has compile-time type
const State *
, there is no difference at all.It is conceivable that the former could be slightly slower if your compiler does not notice that they are compile-time equivalent.
I would avoid the former on the grounds that anybody reading it will wonder what you are thinking.