2010-02-09 70 views
1

我有一個帶有靜態函數的模板類(參見下面的連接函數)。這個模板類是第三方庫(稱爲LibA)的一部分。我的代碼使用這個庫,幷包含下面的頭,因爲我需要使用模板類。當我編譯我的lib沒有內聯函數(-fno-default-inline with gcc)時,我沒有任何問題。當我在release(-O2)編譯時,我的應用程序崩潰。靜態函數,內聯和模板?

我想知道在模板中使用靜態函數的含義以及內聯如何影響此功能。

template<class T> 
class TCPConnector 
: public IOHandler { 
private: 
    string _ip; 
    uint16_t _port; 
    vector<uint32_t> _protocolChain; 
    bool _closeSocket; 
    Variant _customParameters; 
public: 

TCPConnector(int32_t fd, string ip, uint16_t port, 
     vector<uint32_t>& protocolChain, const Variant& customParameters) 
: IOHandler(fd, IOHT_TCP_CONNECTOR) { 
    _ip = ip; 
    _port = port; 
    _protocolChain = protocolChain; 
    _closeSocket = true; 
    _customParameters = customParameters; 
} 

virtual ~TCPConnector() { 
    //FINEST("Close socket: %d", _closeSocket); 
    if (_closeSocket) { 
     close(_fd); 
     //FINEST("Socket closed!"); 
    } 
} 


static bool Connect(string ip, uint16_t port, 
     vector<uint32_t>& protocolChain, Variant& customParameters) { 

    protoent *pProtocol = getprotobyname("IP"); 
    if (pProtocol == NULL) { 
     FATAL("Unable to resolve protocol number for IP"); 
     return 0; 
    } 

    int32_t fd = (int32_t) socket(PF_INET, SOCK_STREAM, pProtocol->p_proto); 
    if (fd <= 0) { 
     FATAL("Unable to create fd"); 
     return 0; 
    } 

    if (!SetFdNonBlock(fd)) { 
     FATAL("Unable to put socket in non-blocking mode"); 
     return false; 
    } 

    TCPConnector<T> *pTCPConnector = new TCPConnector(fd, ip, port, 
      protocolChain, customParameters); 

    if (!pTCPConnector->Connect()) { 
     IOHandlerManager::EnqueueForDelete(pTCPConnector); 
     FATAL("Unable to connect"); 
     return false; 
    } 

    return true; 
} 

};

+0

什麼樣的崩潰發生?段錯誤? – wallyk 2010-02-09 20:28:19

回答

0

它應該沒有關係。一個類的靜態函數是關於你是否需要一個類的實例來調用函數。實際上,非靜態方法和靜態方法之間的主要區別在於前者具有額外的「隱藏」功能參數。

由於您遇到崩潰,您是否確定代碼的哪一部分實際上導致崩潰?

+0

s/format/former/ – 2010-02-09 20:39:35

+0

@MikeDeSimone - 謝謝。 – 2010-02-09 21:16:58

1

我不認爲崩潰與您使用模板,靜態或內聯的事實有關。至少在這種特殊情況下。

您應該嘗試找出墜毀的原因,例如通過分析轉儲。

1

您提示您認爲該庫包含該功能。檢查它是否。如果是這樣,那肯定是一個錯誤。

檢查您的庫文件頭是否有正確的版本。

如果失敗了,那麼可以使用該庫的修復程序可能會從頭中清除定義,因此它不再是內聯。這將使其成爲extern(而不是export)模板化函數,因此您只能在庫.o中使用專門化。

至於你在想什麼,一個靜態成員函數與自由函數鏈接非常相​​似。如果它是內聯的,則不能從庫文件調用。否則,static基本上與extern意思相同:在任何地方只有一個副本。

1

我同意David Alfonso的意見,認爲崩潰可能與您使用這個「圖書館」的事實無關。

而且這個「圖書館」包含不相關的崩潰幾個問題:

  • 目前還不清楚模板參數T.它不會在任何地方使用的目的。
  • 有在連接多個存儲器和資源泄漏()方法:
    • pProtocol和pTCPConnector不會被刪除;
    • fd從不關閉,因爲pTCPConnector未被刪除。