2017-10-11 45 views
0

以下代碼不編譯:克++編譯器的優化:不能轉換 '<大括號包圍的初始化列表>'

#include <sys/socket.h> 
#include <netinet/in.h> 
#include <netinet/tcp.h> 
#include <arpa/inet.h> 
#include <unistd.h> 
#include <fcntl.h> 

namespace net { 

     using Ip = in_addr_t; 
     using Port = in_port_t; 
     using SockFd = int; 

     class Params final { 
     public: 
       Ip getIp() const { return ip_; } 
       Port getPort() const { return port_; } 

     private: 
       Ip ip_ {INADDR_ANY}; 
       Port port_ {htons(5)}; 
     }; 

} 

A.cpp

#include <iostream> 

#include "A.h" 

int main(){ 
     net::Params a {}; 

     std::cout << "Ip=" << a.getIp() << ", Port=" << a.getPort() << std::endl; 

     return 0; 
} 

彙編:

g++-6 -O2 -std=c++11 A.cpp 

錯誤:

In file included from /usr/include/x86_64-linux-gnu/bits/byteswap.h:35:0, 
       from /usr/include/endian.h:60, 
       from /usr/include/ctype.h:39, 
       from /usr/include/c++/6/cctype:42, 
       from /usr/include/c++/6/bits/localefwd.h:42, 
       from /usr/include/c++/6/ios:41, 
       from /usr/include/c++/6/ostream:38, 
       from /usr/include/c++/6/iostream:39, 
       from A.cpp:1: 
A.h:21:15: error: statement-expressions are not allowed outside functions nor in template-argument lists 
    Port port_ {htons(5)}; 
      ^
In file included from A.cpp:3:0: 
A.h:21:23: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘net::Port {aka short unsigned int}’ in initialization 
    Port port_ {htons(5)}; 
        ^

但是,當我改變port_成員變量初始化到:Port port_ {5};,克++與-O2編譯罰款。

上面的代碼編譯沒有優化標誌罰款,是否port_初始化爲:Port port_ {htons(5)};Port port_ {5};

的哪些錯誤?

回答

1

似乎是一個ompiler和/或libstd錯誤。編譯器試圖通過一些宏和編譯器魔法來優化函數調用。這會導致一些我不明白的問題。但是你可以定義一個內聯函數myhtons來調用hton並使用它。用gcc 7.2工作。

inline Port myhtons(Port v) 
    { 
      return htons(v); 
    } 

    class Params final { 
    public: 
      Ip getIp() const { return ip_; } 
      Port getPort() const { return port_; } 

    private: 
      Ip ip_ {INADDR_ANY}; 
      Port port_ { myhtons(5) }; 
    }; 
+0

是的,它的工作原理。謝謝。令人尷尬的是MS的編譯器比GNU更好。 – UDPLover

相關問題