Little gem I found in our code base



  • Types and variables renamed to not give away too much information. ;)

     

    TheClass::TheClass(const TheClass& other){

        if(this){

            m_var = other.m_var;

        }

    }

     

    Can anyone think of a legitimate reason for code like that? Because I sure can't



  • so it would be called TheClass classObj = new TheClass(otherClassObj);

    I've used copy constructors before.  In Java, because of all the pointers flying around behind the scenes, you have to break the object down to its primitive class variables in order to copy it properly.  Otherwise when you modify the classObj object, you're modifying the otherClassObj one.  You can get at private members of another object of type TheClass from within TheClass, I think.  It's been a while since I've needed to.

    Why is it checking whether this is already created (I assume it'll return FALSE if this is null)?  I have no idea.  



  • This is an example of why it would be checked in any other member function:

    class MyClass
    {
    public:
        void DoStuff()
        {
            cout << "In DoStuff, this is " << hex << ((unsigned long)this) << endl;
        }
    };
    

    int main()
    {
    MyClass *mc = NULL;
    mc->DoStuff();

    mc = new MyClass;
    mc-&gt;DoStuff();
    delete mc;
    
    return 0;
    

    }

    However, I have no idea why it would be checked in a constructor. Maybe in case of placement new with NULL.

Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.