gpt4 book ai didi

c++ - 是否可以实现仅 header 的非模板类?

转载 作者:太空狗 更新时间:2023-10-29 21:42:21 24 4
gpt4 key购买 nike

据我了解标准,在不违反单一定义规则的情况下在 header 中实现非模板和非内联的唯一方法是实现这个是匿名命名空间。

但我不确定在此类类方法实现中静态变量会发生什么情况:

// MyHeader.h
// ... pragma once, defines, etc. ...

// (anonymous namespace removed due to suggestions below)
// namespace
// {
class A // a simplified single-threaded kind of Singleton
{
// ... some private not static data ...
public:
static A& instance()
{
static A instance; // is it guaranteed to be module-global?
return instance;
}

void doNothing();
}

// inline added as suggested in answers below
// actually, I disabled inline in compile settings,
// checked that inlining was not happened using disassembler,
// but `inline` keyword is needed and it matters. Any suggestions, why?
inline void A::doNothing()
{
// it's a very long method, so long that I don't want to
// implement it as inline within class body.

// but not so long to consider refactoring it to smaller functions :)
}
//}

// File executable_part1.cpp
// ... includes, etc. ....
A::instance().doNothing();

// File executable_part2.cpp
// ... includes, etc. ....
A::instance().doNothing();

主要问题是:

  • 是否保证 instance 是模块全局的?
  • 此可移植代码或行为是否由编译器实现定义?

我已经在 Windows 的 MSVS 2012 上试验过这段代码。我已将此 header 包含在 3 个模块中每个模块的 2 个 .cpp 文件中:一个可执行文件和 2 个 dll,由可执行文件加载。整体6次。

没有命名空间:constuctor 被调用了 3 次,每个“操作系统级”模块调用一次。With namespace: constuctor 被调用了 6 次,每个 cpp 文件调用一次。

更新:如下所示,C++'03 标准的第 7.1.2 章解决了我的问题。内联在这里很重要。

最佳答案

您不应该使用未命名的命名空间,因为每个翻译单元都有自己的结构 A。

就这样

class A
{
// ... some private not static data ...
public:
static A& instance()
{
static A instance;
return instance;
}

void doNothing();
};

inline void A::doNothing()
{
// it's a very long method, so long that I don't want to
// implement it as inline within class body.

// but not so long to consider refactoring it to smaller functions :)
}
  • exe/dll之间不共享单例是正常的。
  • 使用未命名的命名空间,每个 TU 都有单例,而没有它,单例为整个 exe(以及分别为整个 Dll)共享。

对于您的配置:1 个 exe 和 2 个 cpp,以及 2 个 Dll 和 2 个 cpp:你的实验是正确的:6 个有未命名的命名空间,3 个没有命名空间。

关于c++ - 是否可以实现仅 header 的非模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26534707/

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