簡體   English   中英

對shared_ptr中的const int的未定義引用

[英]undefined reference to const int within shared_ptr

我有一個Config課程

// config.hpp

class Config {
  public:
    static constexpr int a = 1;
    static constexpr int b = 1;
}

並包含在main.cpp中

// main.cpp
#include "config.hpp"
int main () {
  std::cout << Config::a << std::endl; // this is ok
  std::shared_ptr<otherClass> stream = std::make_shared<otherClass>( 
Config::a); // compile error
}

和編譯器說undefined reference to Config::a

它在使用cout ,但在shared_ptr構造函數中不起作用。

我不知道為什么會這樣。

請注意, std :: make_shared通過引用獲取參數,這會導致Config::a使用,因為它將被綁定到引用參數,然后它在命名空間范圍內的定義是必需的(在C ++ 17之前)。

另一方面, std::cout << Config::a不會導致Config::a被使用,因為std :: basic_ostream :: operator <<(int)按值獲取參數, Config::a然后要求lvalue-to-rvalue轉換請求復制初始化參數,因此Config::a不是odr-used。

如果對象使用了odr,則其定義必須存在。 您可以將定義(在實現文件中)添加為

constexpr int Config::a; // only necessary before C++17

請注意,它不能有初始化程序。

生活

由於C ++ 17 constexpr靜態數據成員是隱式內聯的,因此不再需要這樣的定義,因此您的代碼在C ++ 17中運行良好。

如果static數據成員聲明為constexpr ,則它是隱式inline ,不需要在命名空間范圍內重新聲明。 沒有初始化程序(以前需要如上所示)的重新聲明仍然是允許的,但已被棄用。

生活

你的a是私有的,或者是public:需要在它之前或者使類成為一個結構來獲得默認公共。 但這可以在C ++ 14 https://godbolt.org/g/tS4M1Z下編譯

#include <iostream>
#include <memory>

struct Config {
  static constexpr int a = 1;
  static constexpr int b = 1;
};

struct otherClass {
    otherClass( int c ) { }
};

int main () {
  std::cout << Config::a << std::endl; // this is ok
  std::shared_ptr<otherClass> stream = std::make_shared<otherClass>( Config::a ); // compile error
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM