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};
的哪些錯誤?
是的,它的工作原理。謝謝。令人尷尬的是MS的編譯器比GNU更好。 – UDPLover