当我使用以下代码执行1秒的某些操作时,我从Visual Studio收到C4101警告:警告C4101:' highResClock' :未引用的局部变量。当我在声明它之后两次使用highResClock时,我不明白为什么会收到此警告。
chrono::high_resolution_clock highResClock;
chrono::duration<int, ratio<1, 1> > dur(1);
chrono::time_point<chrono::high_resolution_clock> end = highResClock.now() + dur;
while (highResClock.now() < end)
{
// do something repeatedly for 1 second
}
编辑:看起来Visual Studio的警告是因为std :: chrono :: high_resolution_clock :: now()是一个静态函数。访问now()不需要highResClock变量,即使这是我选择使用的特定方法。 Visual Studio似乎将此解释为不使用变量。当我使用以下内容时,我不再收到任何警告:
chrono::duration<int, ratio<1, 1> > dur(1);
chrono::time_point<chrono::high_resolution_clock> end = chrono::high_resolution_clock::now() + dur;
while (chrono::high_resolution_clock::now() < end)
{
// do nothing
}
答案 0 :(得分:8)
您在类的实例上使用静态方法,causes this warning:
但是,当通过类的实例调用静态成员函数时,也会发生此警告:
// C4101b.cpp // compile with: /W3 struct S { static int func() { return 1; } }; int main() { S si; // C4101, si is never used int y = si.func(); return y; }
在这种情况下,编译器使用有关
si
的信息来访问静态函数,但是不需要类的实例来调用静态函数;因此警告 [强调补充]。
MSDN文章还提供了有关如何消除警告的其他信息:
要解决此警告,您可以:
添加一个构造函数,编译器将在
si
的调用中使用func
的实例。从
static
的定义中删除func
关键字。明确调用静态函数:
int y = S::func();
。
由于您使用的是标准类,因此您应该使用后者,例如: std::chrono::high_resolution_clock::now()
:
auto end = std::chrono::high_resolution_clock::now() + std::chrono::seconds(1);
while(std::chrono::high_resolution_clock::now() < end)
{
// do nothing
}
话虽如此,你不应该使用忙循环来等待,还有其他方法可以做到这一点(例如条件变量或std::this_thread::sleep_*
)。