#include <memory>
class CItem
{
private:
int m_inner;
public:
static const int CAP = 1;
CItem(int temp) : m_inner(temp) {}
};
typedef std::shared_ptr<CItem> TPItem;
int main()
{
int tttt = CItem::CAP;
CItem *temp = new CItem(CItem::CAP);
TPItem temp2(temp);
TPItem temp3 = std::make_shared<CItem>(tttt);
TPItem temp4 = std::make_shared<CItem>(CItem::CAP); //On MinGW there error: "undefined reference to `CItem::CAP'"
return 0;
}
- 在 Visual Studio 2012 上它工作正常。
- 在 minGW32 4.9.1 上它说 尝试创建时类的静态常量字段的“ undefined reference ” 与 make_shared 共享指针。
- 其他方法:
- 将此字段复制到 int 并创建与此 int 的共享 - 工作。
- 使用 new - work 创建类对象。
我的错在哪里?
最佳答案
这是因为 CItem::CAP
是 odr-used通过 std::make_shared
(强调我的):
Informally, an object is odr-used if its address is taken, or a reference is bound to it, and a function is odr-used if a function call to it is made or its address is taken. If an object or a function is odr-used, its definition must exist somewhere in the program; a violation of that is a link-time error.
自 std::make_shared通过引用获取其参数,这算作 odr-use。
这意味着您还需要提供类外定义:
const int CItem::CAP ;
或者避免使用 odr,例如本例:
TPItem temp3 = std::make_shared<CItem>(tttt) ;
作为引用,C++11 标准草案 3.2
[basic.def.odr] 说:
An expression is potentially evaluated unless it is an unevaluated operand (Clause 5) or a subexpression thereof. A variable whose name appears as a potentially-evaluated expression is odr-used unless it is an object that satisfies the requirements for appearing in a constant expression (5.19) and the lvalue-to-rvalue conversion (4.1) is immediately applied.
CItem::CAP
是一个常量表达式,在除此之外的所有情况下:
TPItem temp4 = std::make_shared<CItem>(CItem::CAP);
立即应用左值到右值的转换。
关于C++11 MinGW 4.9.1 shared_ptr 和 const 静态类字段结果 "Undefined reference",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803812/