简体   繁体   中英

Weird Behavior of std::cout

I have a class for representing nodes in C++ but when printing the output out to with std::cout I am seeing a weird issue. Here is the class:

class NodeInt
{
    public:
        int value;
        NodeInt* left;
        NodeInt* right;

        NodeInt()
        {
            left    = NULL;
            right   = NULL;
        };

        NodeInt(int val)
        {
            value = val;
            left    = NULL;
            right   = NULL;
        };

        void setValue(int val)
        {
            value = val;
        };

        void insertNode(int val)
        {
            if(val <= value )
            {
                if(left == NULL)
                {
                    NodeInt newNode;
                    newNode.setValue(val);
                    left = &newNode;
                }
                else
                {
                    left->insertNode(val);
                }
            }
            else
            {
                if(right == NULL)
                {
                    NodeInt newNode;
                    newNode.setValue(val);
                    right = &newNode;
                }
                else
                {
                    right->insertNode(val);
                }
            }
        };
};

Here is the main:

int main()
{
    NodeInt firstN;
    firstN.setValue(27);
    firstN.insertNode(11);
    firstN.insertNode(29);
    firstN.insertNode(10);

    /**std::cout << firstN.value << std::endl;
    std::cout << firstN.left->value << std::endl;
    std::cout << firstN.right->value << std::endl;
    **/

    NodeInt* n = firstN.left;
    n = (n->left);
    std::cout << n->value << std::endl;

    return 0;
}

Now you'll see I have three std::cout lines commented out. As it is if I run the program right now it will output the correct value of 10. However, if I un-comment the lines it will change the 10 to 2130567168. Picture is showing what I mean:

在此处输入图片说明

What gives?

You set the two pointers of your Node to point to function-local variables in insertNode() that will be gone when execution reaches the end of the block they are defined in. The output you get is pure luck.

If you want to do manual memory management you'll have to use new and delete and your class needs a copy-constructor, a copy-assignment-operator and a destructor. Please read The Rule of the Big Three (and a half) and The Rule of the Big Four (and a half) (aka The Rule of 3/5).

If you want to have an easier life however you can look up smart-pointers and how to use them and follow The Rule of Zero .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM