gpt4 book ai didi

c++11 chrono 未引用的局部变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:50 25 4
gpt4 key购买 nike

当我使用以下代码执行某些操作 1 秒时,我从 Visual Studio 收到 C4101 警告:warning C4101: 'highResClock' : unreferenced local variable。我不明白为什么在声明后两次使用 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
}

最佳答案

您在一个类的实例上使用静态方法,causes this warning :

However, this warning will also occur when calling a static member function through an instance of the class:

// 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;
}

In this situation, the compiler uses information about si to access the static function, but the instance of the class is not needed to call the static function; hence the warning [emphasis added].

MSDN 文章还提供了如何消除警告的附加信息:

To resolve this warning, you could:

  • Add a constructor, in which the compiler would use the instance of si in the call to func.

  • Remove the static keyword from the definition of func.

  • Call the static function explicitly: 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_*)。

关于c++11 chrono 未引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com