c++ - 通过 char* 返回本地字符串文字

标签 c++ string pointers char string-literals

我有一个模板函数,它将接收一个枚举器并将其转换为 C 风格的空终止字符串。我知道这个程序有一个逻辑错误,因为函数的局部变量通过引用作为返回值传回。但是,程序执行时没有错误或警告 (Visual Studio 17)。这会导致任何未定义的行为或内存泄漏吗?当 str 超出范围时,是否会返回地址的拷贝并销毁指针变量?这是一个好的编程习惯吗?

我能想到的另一个选择是创建动态内存。例如,const char* str = new char[size]

#include <iostream>
#include <string>

namespace Letter {
    enum class Letter {
        AP, // A+
        A,  // A
        BP, // B+
        B,  // B
        CP, // C+
        C,  // c
        DP, // D+
        D,  // D
        F   // F

    };

    template <typename T>
    const char* convertToStr(const T& t) {
        const char* str;

        switch (t) {
        case Letter::AP:
            return str = "A+";
        case Letter::A:
            return str = "A";
        case Letter::BP:
            return str = "B+";
        case Letter::B:
            return str = "B";
        case Letter::CP:
            return str = "C+";
        case Letter::C:
            return str = "C";
        case Letter::DP:
            return str = "D+";
        case Letter::D:
            return str = "D";
        case Letter::F:
            return str = "F";
        default:
            return str = "ERROR: unmatched grade";
        }
    }
}

最佳答案

程序是正确的。字符串文字具有整个程序的生命周期,因此保证始终可用。

但是,该程序不必要冗长。

return str = "ERROR: unmatched grade";

相同
return "ERROR: unmatched grade";

但更干净。

关于c++ - 通过 char* 返回本地字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52723349/

相关文章:

c++ - 使用 glm 沿四元数平移相机

c# - 调用 Caffe 的 C++/CLI 包装器时出现 AccessViolationException

javascript - 了解 Javascript 中空字符串的使用

javascript - 当达到字符限制时,如何在字符串中添加换行符而不破坏单词?

c++ - 为什么 gdb 中的打印命令会为 C++ std::strings 返回\035?

C++ 错误 : no match for ‘operator-=’

C++ 在早期阶段中断一个函数

我可以用分配的内存做我想做的事吗

c++ - 指针算术?这三种表达方式有什么区别?

C++ 指向不在范围内的函数调用的指针