g ++编译器优化:无法转换'<brace-enclosed initializer =“”list =“”>'

时间:2017-10-11 14:37:27

标签: c++11 optimization g++

以下代码未编译:

A.H

#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的g ++编译正常。

以上代码编译没有优化标记,无论port_初始化为:Port port_ {htons(5)};还是Port port_ {5};

怎么了?

1 个答案:

答案 0 :(得分:1)

似乎是一个ompiler和/或libstd错误。编译器尝试使用一些宏和编译器魔法来优化对htons的函数调用。这导致了一些我不明白的问题。但是你可以定义一个调用htons的内联函数myhtons并改为使用它。适用于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) };
    };
相关问题