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 695
自闭症患者
自闭症患者 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

    No, you don't have to use new to return an object from a function. You can return a copy of a local object.

    Q1: Will the node n be destroyed?

    EDIT according to the new code:

    The return type of the function is Node* but you're returning n which is a Node. Your example can't compile. The local Node n will be destroyed at the end of the function, yes. As do all variables with automatic storage (non-static locals).

    Answer according to the old code:

    You have a Node* i.e. a pointer. You try to initialize the pointer with integer 10, but that shouldn't compile. If the code would compile, a copy of the pointer would be returned and the local pointer is destroyed at the end of the function. No Node instances have been created. Dereferencing the returned pointer would have undefined behaviour unless you're absolutely sure that you've allocated a Node instance at the memory address that you initialize the pointer to (which doesn't happen in the shown code).

    Q2: How to write a destructor for the node class?

    It depends on your design. If the memory of Node's is managed by an enclosing class (for example, List) you could choose to do nothing in Node's destructor. If Node is responsible for the linked Node's memory, you'll need to allocate the instances dynamically (with new) and delete in the destructor. Manual deletion is not necessary if you use std::unique_ptr.

提交回复
热议问题