Edu*_*rdo 1 c++ initialization
我收到了这个错误
error: Access.Core may be used uninitialized in this function
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
static int FirstTime = 1;
MyStruct Access;
if (FirstTime) {
FirstTime = 0;
Access = Implementation();
DoSomething(Access);
}
if(Other_Variable) {
Access = Implementation2();
DoSomething(Access);
}
//The Other_Variable will be set to 1 and to 0 by other part of the code
Run Code Online (Sandbox Code Playgroud)
我的代码是这样的,因为我想第一次只调用函数Implementation.在每次调用中,Access变量都将被更新,因此它没有多大意义使其变为静态.
如果我使Access静态工作,但我不喜欢让它静态,因为在每个其他调用Access将被更新.有没有办法避免问题而不使其静止?
此外,欢迎任何更好的选项,只执行一次函数而不是使用静态变量.
做Access这样的(和删除FirstTime和if):
static MyStruct Access = Implementation(this_b);
Run Code Online (Sandbox Code Playgroud)
得到此警告的原因是因为静态变量在一个函数调用中存活.它们的值在所有函数调用中保留(不考虑哪个线程调用该函数).因此,FirstTime将控制您是否初始化Access.第一次调用代码所在的函数将正确初始化Access变量.但是对于每个进一步的函数调用,FirstTime都是零,并且您将不再进行初始化Access,因此将在代码中使用未初始化的变量.
编辑:现在,根据您的更新信息,您说您有两个Implementation功能.第一次使用其中一个时,以及其他所有想要使用其他功能的时间.那么这个怎么样:
// static will be false/zero by default
static bool AlreadyCalled;
MyStruct Access;
if (!AlreadyCalled) {
Access = Implementation();
AlreadyCalled = true;
} else {
Access = Implementation2();
}
Run Code Online (Sandbox Code Playgroud)
但是,根据您的实际使用情况,可能有更好的方法来处理这个问题.例如,为什么不更新状态Access,如下所示:
// let the default constructor initialize it
// to a plausible state
static MyStruct Access;
// use RAII to update the state of Access when this
// function returns.
MyUpdater updater(Access);
// now, do whatever the function does.
Run Code Online (Sandbox Code Playgroud)
这样的东西MyUpdater:
struct MyUpdater {
MyStruct &s;
MyUpdater(MyStruct &s):s(s) { }
~MyUpdater() {
s.ChangeState();
}
};
Run Code Online (Sandbox Code Playgroud)
调用该模式RAII:将一些有用的操作与本地分配的对象的构造函数和析构函数相关联.