C++ allocating dynamic memory in a function - newbie question

前端 未结 7 1585
借酒劲吻你
借酒劲吻你 2021-01-31 12:05

I\'m investigating a memory leak and from what I see, the problem looks like this:

int main(){
    char *cp = 0;
    func(cp);
    //code
    delete[] cp;
}

voi         


        
7条回答
  •  余生分开走
    2021-01-31 12:37

    Although references are wonderful in offering an intuitive abstraction, enhanced further by C++11 rvalue references to allow function chaining (and other esoteric coding), it is arguable that they provide any safety (viz why is a reference considered safer than a pointer) There are instances where it is better to resolve the above with a pointer to pointer function argument. Specifically when there is the need to maintain a similar codebase in ansi c and c++.

    #include 
    
    using namespace std;
    
    void func(char ** cp) {
        *cp = new char[100];
        //do something useful
        (*cp)[0] = 'A';
    }
    
    void func(char *& cp) {
        cp = new char[100];
        //do something useful
        cp[0] = 'B';
    }
    
    int main(int argc, char** argv) {
        char * cp;
        //pointer to pointer
        func(&cp);
        cout << "Index 0 : " << cp[0] << '\n' << flush;
        delete[] cp; //remember to delete!!
        //pointer to ref
        func(cp);
        cout << "Index 0: " << cp[0] << '\n' << flush;
        delete[] cp;
        return 0;
    }
    

    Of course the disposal of memory resources out of the scope of the instatiating function disobeys RAII.

提交回复
热议问题