我的理解是,由于两个问题,虚函数可能会导致性能问题:vtable引起的额外derefencing以及编译器无法在多态代码中内联函数.
如果我将变量指针向下转换为其确切类型怎么办?那还有额外的费用吗?
class Base { virtual void foo() = 0; };
class Derived : public Base { void foo() { /* code */} };
int main() {
Base * pbase = new Derived();
pbase->foo(); // Can't inline this and have to go through vtable
Derived * pderived = dynamic_cast<Derived *>(pbase);
pderived->foo(); // Are there any costs due to the virtual method here?
}
Run Code Online (Sandbox Code Playgroud)
我的直觉告诉我,由于我将对象转换为其实际类型,编译器应该能够避免使用虚函数的缺点(例如,它应该能够内联方法调用,如果它想要).它是否正确?
在我转发后,编译器是否真的知道pderived是Derived类型的?在上面的例子中,看到pbase是Derived类型的微不足道,但在实际代码中它可能在编译时是未知的.
既然我已经写下来了,我想由于Derived类本身可以被另一个类继承,将pbase向下转换为Derived指针实际上并不能确保编译器的任何内容,因此它无法避免成本虚拟功能?
我正在使用PHP filter_input函数来解析HTML表单输入.其中一个输入字段代表金额.我希望我有一些用户使用逗号,有些用点作为小数分隔符.FILTER_VALIDATE_FLOAT过滤器有一个十进制选项,但我还没有找到一种干净的方法来接受这两个字符作为小数分隔符.
目前我的代码看起来像以下行,但这不接受像123.45.
$money = filter_input(INPUT_POST, 'money', FILTER_VALIDATE_FLOAT, array('options' => array('decimal' => ',')));
Run Code Online (Sandbox Code Playgroud)
是否有任何标准/干净的方式接受几种类型的小数分隔符,而不必编写自定义解析函数?