C++11 MinGW 4.9.1 shared_ptr 和 const 静态类字段结果 "Undefined reference"

标签 c++ c++11 static constants mingw32

#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::CAPodr-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/

相关文章:

c++ - 两种类型的模板特化

c++11 - c++ normal_distribution 在不同平台上给出不同的结果

html - 如何将phpBB版 block 转换为静态存档页面?

c++ - 在C++/Unreal Engine 4中访问不同类中的静态变量

c++ - 如何检查 `strcmp`是否失败?

c++ - C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别

C++随机数并在处理时等待所有子级的父级

c++ - 将 multimap 转换为一组集合

c++ - unordered_map 构造函数错误(equal_to 模板函数)

performance - 静态类会导致多核系统出现性能问题吗?