c++ - static const char [] 在类线程安全吗?

标签 c++ multithreading static constants mutex

static const 在类线程中是安全的吗?在下面的代码中,我有 trailingBytesForUTF8,这是一个 static const 字符数组。可能有许多线程拥有它们自己的 CConvertUTF 类的对象实例。当多个线程同时访问同一个 trailingBytesForUTF8 数组时,是否会出现任何可变状态问题,或任何其他线程问题?另请注意,线程永远不会共享 CConvertUTF 类的相同对象实例。

// .h
class CConvertUTF final
{
    private:
        static const char trailingBytesForUTF8[256];
    public:
        bool IsLegalUTF8Sequence(const char *source, const char *sourceEnd);
        bool IsLegalUTF8(const char *source, int length);
};

// .cpp
const char CConvertUTF::trailingBytesForUTF8[256] = {
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
    1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
    2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};

bool CConvertUTF::IsLegalUTF8Sequence(const char *source, const char *sourceEnd) {
    int length = trailingBytesForUTF8[*source]+1;
    if (source+length > sourceEnd) {
    return false;
    }
    return IsLegalUTF8(source, length);
}

bool CConvertUTF::IsLegalUTF8(const char *source, int length) {
    char a;
    const *char = source+length;
    switch (length) {
    default: return false;
    /* Everything else falls through when "true"... */
    case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return false;
    case 2: if ((a = (*--srcptr)) > 0xBF) return false;

    switch (*source) {
        /* no fall-through in this inner switch */
        case 0xE0: if (a < 0xA0) return false; break;
        case 0xED: if (a > 0x9F) return false; break;
        case 0xF0: if (a < 0x90) return false; break;
        case 0xF4: if (a > 0x8F) return false; break;
        default:   if (a < 0x80) return false;
    }

    case 1: if (*source >= 0x80 && *source < 0xC2) return false;
    }
    if (*source > 0xF4) return false;
    return true;
}

最佳答案

只读(常量)变量在被销毁之前始终是线程安全的。由于静态对象仅在程序终止时销毁,因此它们对程序的生命周期是有益的。

唯一的异常(exception)是具有 mutable 成员的对象,但这不适用于 char 数组。

关于c++ - static const char [] 在类线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15435720/

相关文章:

c++ - 如何为托管 C++ 类中的静态变量赋值?

c - 在函数中使用 static

C++ 将代码拆分为多个文件的问题

c++ - 协助乱码翻译

c++ - 如何使用变量名引用数组位置

java - 我应该使用什么作为集合的内存屏障?

c# - 如何在 C# 中锁定 ArrayList 项目级别

c++ - shared_timed_mutex 在 OS X 10.11.2 上不可用?

java - 从 ListSelectionListeners 和 ActionListeners 传递变量

c++ - 欧拉计划 #6 C++