C++:When creating a new objects inside a function and returning it as result, must I use the new operator to create the object?

后端 未结 4 716
自闭症患者
自闭症患者 2020-12-15 10:59

I have two dummy questions which have confused me for a while. I did do some searching online and read through much c++ tutorials, however I cannot find concrete answers.

4条回答
  •  渐次进展
    2020-12-15 11:48

    What you did probably mean is:

    Node* func()
    { 
        Node n(10); 
        return &n;
    }
    

    But that would lead to undefined behavior, as the Node n would be on the stack and not under your control.

    Node* func()
    { 
        Node* n = new Node(10); 
        return n;
    }
    

    That would work, but you would need to free the Node* in your destructor.

    If you can use c++11 features I'd probably go with an std::unique_ptr:

    class Node
    {
       int data;
       std::unique_ptr next;
    }
    std::unique_ptr func()
    { 
        std::unique_ptr n(new Node(10)); 
        return n;
    }
    

    That way your Node would be freed by the destructor of the std::unique_ptr<>.

提交回复
热议问题