簡體   English   中英

使用boost :: shared_ptr訪問靜態成員變量

[英]Accessing static member variable using boost::shared_ptr

我正在嘗試將可運行的C ++代碼從Windows / Visual C ++ 2010移植到Linux(Ubuntu 12.04)平台1

代碼正在嘗試使用boost的shared_ptr訪問靜態成員變量。 當我將此代碼移植到Linux時,我得到: "undefined reference to Test::TYPE" ,即使它可以在Windows上編譯並正常工作。

這是演示錯誤的測試程序:

#include <iostream>
#include <boost/shared_ptr.hpp>

class Test
{
public:
    Test(int x, int y) : a_(x), b_(y) { }

    void print() { std::cout << "a_ : " << a_ << ", b_ : " << b_ <<   std::endl; }

    static const unsigned int TYPE = 5;

private:
    int a_;
    int b_;
};

int main()
{
    boost::shared_ptr<Test> pTest(new Test(10, 20));
    pTest->print();
    std::cout << "Test Type is: " << pTest->TYPE << std::endl;

    return 0;
} 

我想知道為什么GCC為上述代碼提供了未定義的參考?

注意:如果我使用簡單的指針而不是boost shared_ptr它將很好地工作。


1.我正在使用Ubuntu Linux 12.04,gcc版本4.6.4和boost 1.44。

“未定義的引用”是鏈接器錯誤。 顯然,編譯器使用該常量的地址,可能是因為它不夠聰明,無法意識到它始終是相同的常量。

當使用需要常量地址的方式(例如通過引用傳遞它)時,還必須提供常量的定義(在某些.cpp文件中)。

通過共享指針訪問常量似乎比必要的要復雜一些。 使用Test::TYPE將使編譯器更容易。

暫無
暫無

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

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