此代码有效:
char* CFichierTrace::ConvertBSTRToString(BSTR* str) { if ( str == NULL ) { char* buf = new char[2]; sprintf_s(buf, 2, "%s", ""); return buf; } else return _com_util::ConvertBSTRToString(*str); }
但我正在努力避免多次返回,有人告诉我糟糕的编程。然而它只是行不通:
char* CFichierTrace::ConvertBSTRToString(BSTR* str) { // char* result = new char[1]; (attempt #1, produces garbage as output) char* result = (char*) malloc(1 *sizeof(char)); (attempt #2, more garbage as output) if ( str == NULL ) { char* buf = new char[2]; sprintf_s(buf, 2, "%s", ""); result = buf; } else result = _com_util::ConvertBSTRToString((BSTR) str); return result; }
有一篇关于将字符串作为参数中的 char** 返回的文章(通过 ref),但我不明白为什么不能返回堆中的 char*?
最佳答案
char* CFichierTrace::ConvertBSTRToString(BSTR* str)
{
char* ret;
if ( str == NULL )
{
ret = new char[1];
ret[0] = 0;
}
else
ret = _com_util::ConvertBSTRToString(*str);
return ret;
}
顺便说一句,您不应该将 C++ new
与 C malloc
混合使用。
此外,有争议的是,多个返回点是一种不好的做法。在很多情况下,当您有多个返回点时,代码的可读性会更高。
关于c++ - 从函数返回堆字符指针的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23301482/