使用整数指针作为唯一ID有多糟糕?C++ 11

dvi*_*ino 5 c++ multithreading pointers c++11

我得到了一个类,当实例化时需要获得一些独特的ID才能工作.最初我想过使用一个分配和增加的静态函数.我不需要它们是连续的,只是唯一的.

class A {
    int id_1;
    int id_2;
    int id_3;
public:
    static int last_id=0;
    static int get_id(){ return A::last_id++; }
    ...
    A(){ id_1 = A::get_id(); id_2 = A::get_id(); id_3 = A::get_id(); } 
};
Run Code Online (Sandbox Code Playgroud)

现在,我正在考虑进行多线程处理.我认为静态函数将成为一个瓶颈,因为我在开始时构建了几十万个这些对象的实例.我不会在程序结束之前销毁任何实例,因此在初始化之后它们是固定的.无论如何,它们不是在编译时计算的,因为数量取决于命令行参数.

我想到的另一种选择是使用内存地址,它们至少在一台计算机中是独一无二的.

就像是:

class A {
    int* id_1;
    int* id_2;
    int* id_3;
public:
    static int last_id=0;
    static int get_id(){ return A::last_id++; }
    ...
    A(){ id_1 = new int(0); id_2 = new int(0); id_3 = new int(0); } 
    ~A() { delete id_1; delete id_2; delete id_3(); }
};
Run Code Online (Sandbox Code Playgroud)

然后我会读取标识符作为指针的地址.

问题:使用这样的指针是否有意义?

Tra*_*kel 8

你原来的解决方案真的不是那么遥远.不要过早优化!增加一个int非常便宜!我唯一的建议是用std::atomic<int>而不是int.

class A {
    int id_1;
    int id_2;
    int id_3;

    static int get_id() {
        static std::atomic<int> next_id(1);
        return ++next_id;
    }

public:
    A() :
        id_1(get_id()),
        id_2(get_id()),
        id_3(get_id())
    { }

    // deal with copying by disabling
    A(const A&) = delete;
    A& operator=(const A&) = delete;

    // move is okay
    A(A&&) noexcept = default;
    A& operator=(A&&) noexcept = default;
};
Run Code Online (Sandbox Code Playgroud)

假设您不创建多个2^31/3实例A,则不必担心溢出.