Search code examples
c++inheritanceunique-ptrrttitypeid

c++ typeid returns different values for the same unique_ptr with get() and *


I came across one piece of code where typeid is used to get the type of a unique_ptr pointing to a polymorphic object.

class B{virtual void foo()= 0;};
class D:public B{void foo() override{}};

int main()
{
    unique_ptr<B> bd = make_unique<D>();
    if (typeid(*bd) != typeid(bd.get()))
    {
        cout<<"Object types are not same"<<endl;
    }
    cout<<"Type name of *bd.name():      "<<typeid(*bd).name()<<endl;
    cout<<"Type name of bd.get().name(): "<<typeid(bd.get()).name()<<endl;
}

The output is :

Object types are not of same 
Type name of *bd.name():      1D 
Type name of bd.get().name(): P1B

The output of name() is different for get() and dereferencing with *. One more observation is that when there is no virtual functions defined in the class [without void foo() in above example], both get() and * prints same output.

Questions :

Why the get() and * gives different output when there is no virtual functions in the class ?

Live example : https://gcc.godbolt.org/z/Tiy-Cn

EDIT-1 As per * on a unique_ptr, it says "Returns the object owned by *this, equivalent to *get()."


Solution

  • *bd returns a reference.

    bd.get() returns a pointer.


    Re: your edit: Note that it says "equivalent to *get()" and not "equivalent to get()".