Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is a pointer to the return-value of the typeid operator always valid in C++?

I assume it is the case, because e.g. &typeid(int) should be known already at compile-time, i.e. the pointer should never be invalidated when running out of any scope.

Example:
If my assumption is correct, then the following code should not lead to any undefined behavior (at least it works on my PC).

int main() {
    const std::type_info* pType = nullptr; 
    {
        pType = &typeid(int);
    }
    std::cout << pType->name() << std::endl;
}

My goal:
Let’s say I have a class called MyTest defined as follows.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct MyTest {
    const std::type_info* pType;
    MyTest(const std::type_info& type) : pType(&type) {}
    void printType() { std::cout << pType->name() << std::endl; }
};

Then the following code should hopefully lead to no undefined behavior, even when the argument in the constructor of MyTest is just "local".

int main() {
    MyTest myTest(typeid(double));
    myTest.printType();
}

I know there is another thread about whether you can compare two types by comparing the pointers to the return value of typeid, but that is not my problem here.

>Solution :

According to the current draft of the Standard, that’s safe. Two key points found in [expr.typeid]:

  • The result of a typeid expression is an lvalue .
  • The lifetime of the object referred to by the lvalue extends to the end of the program

https://eel.is/c++draft/expr.typeid#1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading