gpt4 book ai didi

c++ - 静态变量 : Construction happens after usage

转载 作者:行者123 更新时间:2023-11-28 02:30:03 27 4
gpt4 key购买 nike

我正在 Visual Studio 2013 的控制台应用程序中进行一些测试。涉及静态变量,我看到一些奇怪的行为。主要问题是 GenericFactory 模板类的静态 Printer 成员是在我使用它之后构造的(在其 Register函数)!

关于全局/静态变量和初始化顺序的规则非常复杂,所以有人可以帮我理解这里出了什么问题吗?代码如下。

ma​​in.cpp:

#include <iostream>

int main()
{
std::cout << "Main Function\n";
}

通用工厂.hpp:

#pragma once

#include <functional>
#include <map>
#include <memory>
#include <iostream>

class Printer
{
public:
Printer()
{
std::cout << "Printer class created\n";
}

void Stuff()
{
std::cout << "Printer Stuff, Address " << (int)this << "\n";
}
};

template<typename Key>
class GenericFactory
{
public:

static Key const& Register(Key const& key)
{
GenericFactory::s_printer.Stuff();
std::cout << "Registered: " << key << "\n";
return key;
}

private:
static Printer s_printer;
};

template<typename Key>
Printer GenericFactory<Key>::s_printer;

StringFactory.hpp:

#pragma once

#include <string>
#include "GenericFactory.hpp"

using StringFactory = GenericFactory<int>;

test1.cpp:

#include "StringFactory.hpp"

namespace Other
{
static auto key = StringFactory::Register(100);
}

test2.cpp:

#include "StringFactory.hpp"

namespace Other
{
static auto key = StringFactory::Register(200);
}

运行上述应用程序后得到的输出:

Printer Stuff, Address 3422532
Registered: 100
Printer class created
Printer Stuff, Address 3422532
Registered: 200
Main Function

请注意,"Printer Stuff, ...""Printer class created" 之前打印。我在这里要疯了吗?

最佳答案

您假设全局变量的构造顺序。这不是一个好方法。尝试将其更改为类似的东西(不是最干净的,但说明了这一点):

template<typename Key>
class GenericFactory
{
static Printer& printer()
{
static Printer s_printer;
return s_Printer;
}
public:


Key const& Register(Key const& key) // removed static here.
{
printer().Stuff();
std::cout << "Registered: " << key << "\n";
return key;
}

};

编辑:

这是我用于不需要多线程双锁保护的单例的典型模式:

#include <memory>

class MySingletonClass
{
public:
static MySingletonClass* instance()
{
static std::unique_ptr<MySingletonClass> ptr(new MySingletonClass);
return ptr.get();
}

// Public functions here

private:
friend struct std::default_delete<MySingletonClass>;
// Hide these to avoid unintentional copy
MySingletonClass() {}
~MySingletonClass() {}
MySingletonClass(const MySingletonClass&) {}
MySingletonClass& operator= (const MySingletonClass&) { return *this; }
};

如果你也想加入线程安全,搜索一下可以找到很多文章: https://www.google.com/search?q=singleton+c%2B%2B+double+checked+locking

关于c++ - 静态变量 : Construction happens after usage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286344/

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