由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - [请教] C++ coding question
相关主题
one C++ questionC/C++里数组作函数的参数的话应该怎么写?
C++ Q47: protected constructor (C39)请教一个OOP的C++问题
One C++ questionA question about C++. Thanks.
one C/C++ question问一道C# interview testing quesiton
C++ 一问?问一道c++面试题
微软C++面试题关于java synchronized statement和static method or variable
C++继承问题请问这段程序有什么bug?
问个c++的问题关于singleton 的面试题
相关话题的讨论汇总
话题: myclass话题: counter话题: c++话题: static
进入JobHunting版参与讨论
1 (共1页)
s****u
发帖数: 375
1
在类的定义文件myClass.cpp里,有一个non-member静态函数。有什么办法能保证这个
静态函数只被该类型的(无数多个)instances调用最多一次?
比如下面这个例子就不满足以上要求, 因为结果counter大于1.
static int counter = 0;
static void nonMemberFunction()
{
counter += 1;
}
class myClass
{
public:
myClass() { nonMemberFunction(); }
};
int main()
{
myClass A;
myClass B;
std::cout< return 0;
}
x***i
发帖数: 7
2
static void nonMemberFunction()
{
static bool first = true;
if (first)
counter += 1;
first = false;
}
p*u
发帖数: 2454
3
use singleton, call the method in ctor

【在 s****u 的大作中提到】
: 在类的定义文件myClass.cpp里,有一个non-member静态函数。有什么办法能保证这个
: 静态函数只被该类型的(无数多个)instances调用最多一次?
: 比如下面这个例子就不满足以上要求, 因为结果counter大于1.
: static int counter = 0;
: static void nonMemberFunction()
: {
: counter += 1;
: }
: class myClass
: {

w***u
发帖数: 156
4
agree

【在 p*u 的大作中提到】
: use singleton, call the method in ctor
s**x
发帖数: 7506
5

加上lock 就行了。

【在 x***i 的大作中提到】
: static void nonMemberFunction()
: {
: static bool first = true;
: if (first)
: counter += 1;
: first = false;
: }

w********s
发帖数: 1570
6
std::call_once(xxx, once_flag);

【在 s****u 的大作中提到】
: 在类的定义文件myClass.cpp里,有一个non-member静态函数。有什么办法能保证这个
: 静态函数只被该类型的(无数多个)instances调用最多一次?
: 比如下面这个例子就不满足以上要求, 因为结果counter大于1.
: static int counter = 0;
: static void nonMemberFunction()
: {
: counter += 1;
: }
: class myClass
: {

s**x
发帖数: 7506
7

这个更好!

【在 w********s 的大作中提到】
: std::call_once(xxx, once_flag);
u**l
发帖数: 35
8


【在 w********s 的大作中提到】
: std::call_once(xxx, once_flag);
1 (共1页)
进入JobHunting版参与讨论
相关主题
关于singleton 的面试题C++ 一问?
singleton pattern problem微软C++面试题
最新微软SDE II面试题C++继承问题
请问一道special singleton class的题问个c++的问题
one C++ questionC/C++里数组作函数的参数的话应该怎么写?
C++ Q47: protected constructor (C39)请教一个OOP的C++问题
One C++ questionA question about C++. Thanks.
one C/C++ question问一道C# interview testing quesiton
相关话题的讨论汇总
话题: myclass话题: counter话题: c++话题: static