gpt4 book ai didi

c++ - 如何处理静态存储时长警告?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:12 26 4
gpt4 key购买 nike

我是一个试图从书中学习 C++ 的新手。下面的代码按预期工作并产生输出,但在定义 enginerandomInt 的两行上有警告:“Initialization of 'engine' with static storage duration may throw无法捕获的异常。”

如果我将第 7 行和第 8 行放在 main() 中,警告就会完全消失,但是 enginerandomInt 不会可用于 getNumber

我不知道如何修复这些警告。此外,也许更重要的是,除了 main() 之外,在不同地方使用 randomInt 的正确方法是什么?在 main() 中声明它然后根据需要将其传递给函数是否合适?不知何故 main() 感觉不适合声明这些类型的东西。

我之前问过一个与此类似的问题,但我仍在努力理解,并提供了一个希望有用的示例。

// Loosely based on Fig. 6.12: fig06_12.cpp, C++ How To Program, Ninth Edition

#include <iostream>
#include <iomanip>
#include <random>

std::default_random_engine engine( static_cast<unsigned int>( time(nullptr) ) );
std::uniform_int_distribution<unsigned int> randomInt( 1, 6 );

int getNumber();

int main() {
for ( unsigned int counter = 1; counter <= 10; ++counter ) {
std::cout << std::setw( 10 ) << randomInt( engine );
if ( counter % 5 == 0 )
std::cout << std::endl;
}
std::cout << getNumber() << std::endl;
return 0;
}

int getNumber () {
return randomInt( engine );
}

输出:

/CLionProjects/Warning/cmake-build-debug/Warning
3 5 6 3 3
1 4 2 4 5
2

Process finished with exit code 0

最佳答案

延迟初始化全局变量(例如您正在使用的变量)的一种方法是将它们包装在 get 函数中。

std::default_random_engine& getEngine()
{
// Initialized upon first call to the function.
static std::default_random_engine engine(static_cast<unsigned int>(time(nullptr)));
return engine;
}

std::uniform_int_distribution<unsigned int>& getRandomInt()
{
// Initialized upon first call to the function.
static std::uniform_int_distribution<unsigned int> randomInt(1, 6);
return randomInt;
}

然后使用 getEngine()getRandomInt() 而不是直接使用变量。

关于c++ - 如何处理静态存储时长警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48938090/

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