gpt4 book ai didi

c++ - 存储指向静态变量的指针

转载 作者:太空狗 更新时间:2023-10-29 20:51:18 25 4
gpt4 key购买 nike

我已经为 C++ 创建了一个单元测试框架,稍后我想将其移植到 C,但我遇到了单元测试根本无法运行的问题。单元测试在 .cpp 文件中创建,并且只有一个 .cpp 文件应该运行所有测试。

为了简化一点,测试通常是这样创建的:

main.cpp

#define UNIT_TEST_IMPL // or whatever
#include "unit_test.hpp"

int main()
{
for(const auto& test : tests_queue)
test->run();
return 0;
}

单元测试.hpp

#pragma once

struct Base
{
protected:
Base() = delete;
Base(Base* ptr);

public:
virtual void run() = 0;
};

#if defined(UNIT_TEST_IMPL)

#include <vector>

std::vector<Base*> tests_queue;

Base::Base(Base* ptr)
{
tests_queue.push_back(ptr);
}

#endif

测试.cpp

#include "unit_test.hpp"

#include <iostream>

struct Test : Base
{
Test()
: Base(this)
{}

void run() override
{
std::cout << "new test" << std::endl;
}

};

struct Test2 : Base
{
Test2()
: Base(this)
{}

void run() override
{
std::cout << "new test2" << std::endl;
}
};

static Test test;
static Test2 test2;

问题是:为什么它不运行 test.cpp 中定义的测试(如果我在 main.cpp 文件中创建测试,它们运行得很好)?我的猜测是问题出在我存储 Base 指针的方式上,但我不知道。编译器是g++ 6.4.0

最佳答案

static-initialization-order-fiasco 的实际应用:

全局跨翻译单元的初始化顺序是未指定的,所以如果testtest2tests_queue之前被实例化,后面的初始化会破坏注册。

一个可能的更正:

#pragma once

struct Base
{
protected:
Base();

public:
virtual ~Base() = default;
virtual void run() = 0;
};

#if defined(UNIT_TEST_IMPL) // Should be defined only once.

#include <vector>

std::vector<Base*>& get_tests_queue()
{
static std::vector<Base*> tests_queue;
return tests_queue;
}

Base::Base()
{
get_tests_queue().push_back(this);
}

#endif

所以你的 main.cpp 将是:

#define UNIT_TEST_IMPL // or whatever
#include "unit_test.hpp"

int main()
{
for(const auto& test : get_tests_queue())
test->run();
}

您的单元测试将保持不变:

#include "unit_test.hpp"

#include <iostream>

struct Test : Base
{
void run() override { std::cout << "new test" << std::endl; }
};

struct Test2 : Base
{
void run() override { std::cout << "new test2" << std::endl; }
};

static Test test;
static Test2 test2;

Demo

关于c++ - 存储指向静态变量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50747082/

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