Tim_King
Tim_King

Reputation: 135

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.

I have a trivial Base class as follows

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& ChangeBase(Base &b)
{
    std::cout<<"Called"<<std::endl;
    return b;
}

When I wrote following codes to examine typeid operator:

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)? If yes, why?

I'm using gcc 4.9.3

Upvotes: 3

Views: 87

Answers (1)

Zefick
Zefick

Reputation: 2119

GCC first check value for being null then evaluated it again and only after that calls typeid.

Assembly: 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

Upvotes: 2

Related Questions