我正在尝试在 Node.js 中实现我自己的 promise 版本以用于实践目的。 我得到了我不明白的结果。 我创建了以下代码来显示我的问题是什么。 我收到错误消息'TypeError: Cannot read property 'name' of undefined' 。 当我调用构造函数时, ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我有两个常量文件:
// constants.h
extern const std::string testString;
// constants.cpp
const std::string testString = "defined!";
程序初始化时,我需要在对象的构造函数中使用此常量,但是它是未定义的。 构造函数中的代码是:
MyClass::MyClass() {
printf("Value of test string: %s", testString.c_str());
}
// output:
Value of test string: (null)
类和常量在同一个命名空间中定义,并且不会给我一个错误,即常量未定义。 初始化对象后(例如,使用硬编码的字符串),它可以正常工作并打印出常量的值(“ defined!”)。 原始常量在构造函数中似乎可以正常工作。
我认为这与当时未初始化的常量有关(因此来自.cpp文件)。 你知道为什么会这样吗? 在程序完全初始化之后,是否会进行extern const的初始化?
先感谢您
编辑:
请注意, string
类型是为了简化问题,因此将其转换为char
不是一个选择,因为我也对拥有其他非基本类型感兴趣。
显示此问题的程序的最小脏例代码:
// constants.h
extern const std::string testString;
// constants.cpp
#include "constants.h"
const std::string testString = "defined!";
// MyClass.h
class MyClass {
public:
MyClass();
virtual ~MyClass();
};
// MyClass.cpp
#include "MyClass.h"
#include "constants.h"
MyClass::MyClass() {
printf("Value of test string: %s\n", testString.c_str());
}
MyClass::~MyClass() {}
// main.cpp
#include "MyClass.h"
#include "constants.h"
MyClass my; // undefined string (outputs null)
int main(int argc, char** argv) {
MyClass my; // defined string
return 0;
}
编辑2:
在这种情况下,解决方案是在头文件中定义静态内联函数,如@Brian和@LightnessRacesinOrbit建议的那样。 他们都为最终答案做出了贡献。
这是代码:
inline std::string getTestString() { return "defined!"; }
这允许将非constexpr
类型作为全局常量。
在 constants.cpp
转换单元内,将在随后定义的任何非局部变量之前初始化testString
。 在翻译单元之间 ,我们有所谓的“静态初始化顺序惨败”; 除了constants.cpp
之外的任何转换单元都不能假设testString
已初始化,直到main
开始执行之后,因此,如果它尝试在其自身的非本地初始化之一期间读取其值,则它可能会观察到零初始化的std::string
对象,其行为未定义。
我建议避免这个问题(这也是我以前的工作场所所遵循的规则)的建议是,如果您必须具有全局常量,请尽可能使它们成为constexpr
,并非常警惕任何非constexpr
全局变量。 std::string
不是constexpr
(尚未),但是老式的char
数组可以工作:
// constants.h
inline constexpr char testString[] = "defined!";
// constants.cpp
// no need to define `testString` here!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.