samedi 19 décembre 2020

Why there is something wrong when invoking ctor in another ctor?

Here is a demo code snippet(https://godbolt.org/z/31Tq3r):

 #include<iostream>

class Ctx
{
public:
    enum RUN_MOD
    {
        MOD_RT,
        MOD_NRT,
    };

    Ctx(RUN_MOD runType)
    {
        if(runType == MOD_RT)
        {
            Ctx();
        }
    }

    Ctx()
    {
        m_L = malloc(100);
        std::cout << "set m_L=" << m_L << std::endl;
    }

    void print()
    {
        std::cout <<"print() m_L=" << m_L << std::endl;
    }

private:
    void *m_L;

    const char* const ARG_TYPE_NOT_MATCH = "the type of argument is not match";
    const char* const ARG_NUM_INVALID = "the number of arguments is invalid";
    const char* const STACK_OPS_INPUT_ARG_INVALID = "the input argument passed to the stack ops is invalid";
};


int main()
{
    Ctx ctx(Ctx::RUN_MOD::MOD_RT);

    ctx.print();
}

Here are outputs when invoking the binary program on Ubuntu:

set m_L=0x614c20 
print() m_L=0x400ad0

You see the addresses are not the same. I have set m_L by invoking Ctx::Ctx()(which is called by Ctx::Ctx(RUN_MOD runType)) indeed. I am really confused.

Aucun commentaire:

Enregistrer un commentaire