#include <iostream>
#include <string>
#include <ctime>
#include <unistd.h>
using namespace std;
unsigned get_rand() {
srand(unsigned(time(0)));
return rand() % 1000;
}
class numbered {
public:
numbered()
: mysn(get_rand()), name(to_string(mysn)) {}
numbered(const numbered &n)
: mysn(get_rand()), name(n.name) {}
numbered &operator=(const numbered &n) {
mysn = get_rand();
name = n.name;
return *this;
}
~numbered() {
cout << mysn << " with name " << name << endl;
}
unsigned get_sn() {return mysn;}
private:
unsigned mysn;
string name;
};
void fun(numbered s) { cout << s.get_sn() << endl;}
int main() {
numbered a;
sleep(1);
numbered b = a;
sleep(1);
numbered c = b;
sleep(1);
fun(a);
sleep(1);
fun(b);
sleep(1);
fun(c);
}
如果没有自定义的拷贝和赋值运算符,对象所有的成员都会被拷贝,包括唯一的ID号码。
本文探讨了C++中使用随机数生成唯一ID的技巧,并通过自定义拷贝构造函数和赋值运算符来防止对象状态的不当复制。展示了如何在类中实现这些功能,以及它们在多线程环境下的潜在问题。

被折叠的 条评论
为什么被折叠?



