c++ - 从函数返回堆字符指针的问题

标签 c++

此代码有效:


        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/

相关文章:

c++ - 如何在行编辑 Qt Creator 中设置文本?

c++ - pthread_create() 调用的函数的多个参数 - 参数是函数指针

c++ - 将 float 与参数内的字符串连接起来

c++ - 缩放矩阵和平移矩阵相关问题

c++ - 如何根据不同的参数定义相同的宏函数

c++ - 重构:在 CLion 中移动 (F6) - 为什么它会这样工作?

c++ - gcc 和 g++ 库搜索路径

c++ - std::map emplace 因显式构造函数而失败

c++ - 在 libharu 中将长字符串转换为多行字符串

c++ - 如何在C++中解析引号和逗号