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

后端 未结 7 597
我寻月下人不归
我寻月下人不归 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:00

    You must not pass a null pointer to the constructor of a std::string, so you must check the buffer pointer getcwd() returns isn't null. Also, the buffer pointer you pass to getcwd() must not be null.

    std::string getcwd() {
        char buf[FILENAME_MAX];
        char* succ = getcwd(buf, FILENAME_MAX);
        if( succ ) return std::string(succ);
        return "";  // raise a flag, throw an exception, ...
    }
    

提交回复
热议问题