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 706
自闭症患者
自闭症患者 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:49

    You can return pointer to local object, but it will be pointed to stack memory, so results may be suprising. Look the following code:

    #include 
    
    using namespace std;
    
    class Node { public: int n; };
    
    Node* create(int n) {
        Node node = Node();
        node.n = n;
        cout << "Created " << node.n << endl;
        return &node;
    }
    
    int main() {
       Node* n1 = create(10);
       Node* n2 = create(20);
       cout << "Reading " << n1->n << endl;
       cout << "Reading " << n2->n << endl;
       return 0;
    }
    

    You won't get "10" "20" output. Instead

    Created 10
    Created 20
    Reading 20
    Reading 1891166112
    

    First object was destructed (when first create function call ended). Second object was created on top of destructed n1, so n1 address was equal to n2 address.

    Compiler will warn you when you return stack addresses:

    main.cpp: In function Node* create(int):
    main.cpp:8:10: warning: address of local variable node returned [-Wreturn-local-addr]
         Node node = Node();
    

提交回复
热议问题