Show pointer when passing by reference

Look at my code, I can put a pointer GoodManon a pointer Manand go to a function AddManusing two steps. But when I use one step for this, it does not work. Instead, it needs to explicitly specify Man a pointer link, not just a pointer Man. What is the reason for this?

    class Man{
    };

    class GoodMan: public Man
    {
    };

    void AddMan(Man*& man){};

    int main()
    {
        GoodMan* good_man = new GoodMan() ;

        //This works
        Man* pMan2 = (Man*)good_man;    
        AddMan(pMan2);

        //So I think this should work, But doesn't work
        AddMan((Man*)good_man);

        //But this works
        AddMan((Man*&)good_man);

        return 0;
    }
+4
source share
4 answers

AddMan((Man*&)good_man);causes undefined behavior. This is a smoothing GoodMan *like Man *, which is unacceptable. That reinterpret_cast.

Although GoodManderived from Man, is GoodMan *not "derived" from Man *, they are incompatible types.

Example:

AddMan(static_cast<Man*&>(good_man));   // error: invalid static_cast

AddMan(reinterpret_cast<Man*&>(good_man));   // no error, but runtime UB

"" , void AddMan(Man*& man);. Man *. , Man *. Man * . , ? good_man Man *.

+3

++ rvalues ​​(bacically temporaries), s (Man*)good_man lvalue, Man*&. pMan2 lvalue, AddMan. (Man*)good_man - r. .

AddMan, const lvalue, .

void AddMan(Man* const& man){};

, , . , , lvalue, "" , . , AddMan.

AddMan((Man*&)good_man); // "works" by pretending everything is OK. It isn't.
+9

, (Man*)good_man r- (.. ), (Man*&)good_man pMan2 l-values ​​.

:

  • l-value Man&= l-
  • r-value Man&&= r-
  • const l-value const Man&=
  • const r-value const Man&&= r-

As a parameter to the function, you have an l-value reference , so it can only bind to l-value .

Thanks for reading.

+1
source

(Man*)good_manis rvalueand therefore cannot be attached to a link Man*. (Man*&)good_man, on the other hand, is already passed to a compatible type and works great. Please note: if you change the signature AddManto take a link to const, all your examples will work fine.

0
source

Source: https://habr.com/ru/post/1568712/


All Articles