简体   繁体   English

typeid中的表达式在运行时被评估两次?

[英]expression in typeid is evaluated twice in runtime?

Note that expression in typeid operator would be evaluated in runtime if it is a lvalue of a type with virtual member. 请注意,如果typeid运算符是具有virtual成员的类型的左值,则它将在运行时计算。

I have a trivial Base class as follows 我有一个简单的Base类如下

class Base
{
public:
    Base(const std::string &s):sval(s){}
    virtual ~Base()=default; 
private:
    std::string sval;
};

and a trivial function to return a lvalue of Base as follows: 还有一个简单的函数来返回Base的左值,如下所示:

Base& ChangeBase(Base &b)
{
    std::cout<<"Called"<<std::endl;
    return b;
}

When I wrote following codes to examine typeid operator: 当我编写以下代码来检查typeid运算符时:

int main()
{

    Base b("Dream");
    typeid (ChangeBase(b));
    return 0;
}

I got following output: 我得到以下输出:

Called
Called

It indicated that function ChangeBase was called twice, so did it mean that expression in typeid would be evaluated twice in runtime (if need to evaluate in runtime)? 它表示函数ChangeBase被调用了两次,所以它是否意味着在运行时将对typeid中的表达式求值两次(如果需要在运行时进行求值)? If yes, why? 如果是,为什么?

I'm using gcc 4.9.3 我正在使用gcc 4.9.3

GCC first check value for being null then evaluated it again and only after that calls typeid. GCC首先检查值为null,然后再次对其进行评估,并且仅在调用typeid之后。

Assembly: https://godbolt.org/g/SoLFYq 大会: https//godbolt.org/g/SoLFYq

    lea     rax, [rbp-64]
    mov     rdi, rax
    call    ChangeBase(Base&)
    test    rax, rax
    je      .L8
    lea     rax, [rbp-64]
    mov     rdi, rax
    call    ChangeBase(Base&)
...
.L8:
    call    __cxa_bad_typeid

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

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