内联函数中的静态局部变量导致 VS2015 编译代码挂起
static local variable in inline function causes hang in VS2015-compiled code
我有一个沿用这些行的遗留代码:
inline A::A() {
static boost::shared_ptr<Data> data(new Data(""));
data_ = data;
}
Data
是一些class而data_
是class A
的非静态成员变量。我不确定这里原始编码器的想法是什么,但有趣的是,这段代码在使用 Visual Studio 2013 构建时工作正常,但是当它使用 Visual Studio 2015 构建时,代码挂起(在初始化静态变量 data
的行上)在 DLL 加载时。
在加载 DLL 时调用代码的原因是存在 class A
的静态对象,例如
class B
{
static A a_;
}
我意识到 VS2015 可能会以不同方式构建代码,例如,不遵守内联提示等。但是它挂起的原因是什么?这是一些内存损坏吗?
不是试图让这段代码工作 - 而是试图理解这段代码可能导致的潜在问题。
感谢 David Schwartz 在对原始问题的评论中提出解决方案。
正如我假设的那样,问题不是由于构造函数中 static
局部变量和 inline
提示的任何交互。相反,问题是 Data
的构造函数的调用,因为 Data
有一个 A
类型的成员变量。这会导致循环(A
,要创建,需要 Data
,这需要 A
)
该问题通过使用 Named Constructor Idiom 解决:
class A{
public:
static A createDefault()
{
static boost::shared_ptr<Data> data(new Data(""));
A a;
a.data_ = data;
return a;
}
protected:
//Make the c'tor protected so that nobody uses it by mistake (except for derived classes)
A(){}
//Struct Data can access A::A():
struct Data{
A a_;
Data(string str)
{
//...
}
//...
};
};
其他地方:
//...
A a(A::createDefault());//or similar
//...
剩下的一个谜是 VS2013 如何设法构建它,使代码 运行 正常。
我有一个沿用这些行的遗留代码:
inline A::A() {
static boost::shared_ptr<Data> data(new Data(""));
data_ = data;
}
Data
是一些class而data_
是class A
的非静态成员变量。我不确定这里原始编码器的想法是什么,但有趣的是,这段代码在使用 Visual Studio 2013 构建时工作正常,但是当它使用 Visual Studio 2015 构建时,代码挂起(在初始化静态变量 data
的行上)在 DLL 加载时。
在加载 DLL 时调用代码的原因是存在 class A
的静态对象,例如
class B
{
static A a_;
}
我意识到 VS2015 可能会以不同方式构建代码,例如,不遵守内联提示等。但是它挂起的原因是什么?这是一些内存损坏吗? 不是试图让这段代码工作 - 而是试图理解这段代码可能导致的潜在问题。
感谢 David Schwartz 在对原始问题的评论中提出解决方案。
正如我假设的那样,问题不是由于构造函数中 static
局部变量和 inline
提示的任何交互。相反,问题是 Data
的构造函数的调用,因为 Data
有一个 A
类型的成员变量。这会导致循环(A
,要创建,需要 Data
,这需要 A
)
该问题通过使用 Named Constructor Idiom 解决:
class A{
public:
static A createDefault()
{
static boost::shared_ptr<Data> data(new Data(""));
A a;
a.data_ = data;
return a;
}
protected:
//Make the c'tor protected so that nobody uses it by mistake (except for derived classes)
A(){}
//Struct Data can access A::A():
struct Data{
A a_;
Data(string str)
{
//...
}
//...
};
};
其他地方:
//...
A a(A::createDefault());//or similar
//...
剩下的一个谜是 VS2013 如何设法构建它,使代码 运行 正常。