How return a std::string from C's “getcwd” function

后端 未结 7 532
我寻月下人不归
我寻月下人不归 2021-01-20 07:35

Sorry to keep hammering on this, but I\'m trying to learn :). Is this any good? And yes, I care about memory leaks. I can\'t find a decent way of preallocating the char*, be

7条回答
  •  星月不相逢
    2021-01-20 08:13

    You're supposed to use the ISO C++ conformant version _getcwd I think. There's no point returning a const string, and you should use free to deallocate (at least according to MSDN):

    string getcwd()
    {
        char* a_cwd = _getcwd(NULL, 0);
        string s_cwd(a_cwd);
        free(a_cwd);
        return s_cwd;
    }
    

    Of course you should also check if _getcwd() returns NULL.

提交回复
热议问题