gpt4 book ai didi

c++ - 如何知道 main() 是否正在运行?

转载 作者:行者123 更新时间:2023-11-30 05:30:14 26 4
gpt4 key购买 nike

上下文:在我的应用程序中,我有一些使用全局变量的函数。由于全局变量的分配顺序未定义,我想在 main 函数运行之前禁止调用这些函数。目前,我只在 Doxygen 中通过 \attention 记录它,但我想添加一个断言。

我的问题:有没有一种优雅的方法可以知道 main 函数尚未运行?

示例 (uniqid.cpp):

#include <boost/thread.hpp>
#include <cassert>
unsigned long int uid = 0;
boost::mutex uniqid_mutex;
unsigned long int uniquid()
{
assert(main_is_running() && "Forbidden call before main is running");
boost::mutex::scoped_lock lock(uniqid_mutex);
return ++uid;
}

我的第一个(丑陋的)想法:我的第一个想法是检查另一个具有特定值的全局变量。那么初始化前变量中有这个值的概率就很小了:

// File main_is_running.h
void launch_main();
bool main_is_running();

// File main_is_running.cpp
unsigned long int main_is_running_check_value = 0;
void launch_main()
{
main_is_running_check_value = 135798642;
}
bool main_is_running()
{
return (main_is_running_check_value == 135798642);
}

// File main.cpp
#include "main_is_running.h"
int main()
{
launch_main();
// ...
return 0;
}

有更好的方法吗?

请注意,我不能使用 C++11,因为我必须与 gcc 4.1.2 兼容。

最佳答案

如果static std::atomic<bool> s;已定义,以及一些切换 struct :

struct toggle
{
toggle(std::atomic<bool>& b) : m_b(b)
{
m_b = true;
}
~toggle()
{
m_b = false;
}
std::atomic<bool>& m_b;
};

然后,在main , 写 toggle t(s);作为第一个声明。这是将引用作为成员变量的一个好主意。

s然后可以告诉你你是否在main或不。使用 std::atomic考虑到 main 的行为可能有点矫枉过正在 C++ 中调用自身是 undefined。如果你没有 C++11,那么 volatile bool足够了:有效地你不在 main 中直到该额外语句完成。

关于c++ - 如何知道 main() 是否正在运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36057111/

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