c++ - 从外部函数访问外部结构属性

标签 c++ struct extern

我在玩了一下外部变量,想知道为什么我无法从外部函数访问外部结构?

这是我的代码:

啊啊

struct testing {

   unsigned int val;
   const char* str;

   testing(unsigned int aVal, const char* aStr) : val(aVal), str(aStr){};
}

extern testing externalStruct;

交流

#include "a.h"

testing externalStruct(10, "test");

测试.c

#include <iostream>
#include "a.h"

unsigned int valCopy = externalStruct.val;
const char* strCopy = externalStruct.str;

int main()
{
   std::cout<<"Direct val : "<<externalStruct.val<<std::endl; // Working, print 10
   std::cout<<"Direct str : "<<externalStruct.str<<std::endl; // Working, print "test"
   std::cout<<"Copy val : "<<valCopy<<std::endl; // Print 0 instead of 10
   std::cout<<"Copy str : "<<strCopy<<std::endl; // Print nothing

   return 0;
}

有什么想法吗?

最佳答案

此问题是由于静态(全局)变量的初始化顺序未知引起的。它甚至还有一个名字static initialization order fiasco 。这意味着 test.c 翻译单元中的全局变量在 a.c 翻译单元中的全局变量之前初始化。

通常的解决方案是使用带有静态变量的函数。当函数被调用时,静态变量(在第一次使用期间)被初始化。使用 c++11 初始化此类静态函数局部变量是线程安全的。

您的代码解决方案可能如下所示:

啊啊

//...

testing& GetExternalStruct();

交流

//...

testing& GetExternalStruct() {
   static testing externalStruct(10, "test");
   return externalStruct;
}

测试.c

unsigned int valCopy = GetExternalStruct().val;
const char* strCopy = GetExternalStruct().str;

关于c++ - 从外部函数访问外部结构属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720724/

相关文章:

c++ - 读写bin文件数据不对

将指向结构的指针转换为指向带有 const 成员的结构的指针

go - 使用值创建结构实例

c - C中同名的外部变量和全局变量

c++ - 在不同文件中使用相同的变量(使用 extern)

c++ - 我可以将 "token pasting operator"与 'const' 模板参数一起使用吗?

c++ - 惯用 std::auto_ptr 还是只使用 shared_ptr?

c++ - 在运行时 boost 异常

c++使用结构中的指针保存和加载游戏

c++ - extern 在 C++ 中的静态函数