2

Can somebody tell me the difference between #pragma pack(push,1) and __attribute__((packed))? I am getting a compilation error if I use second type of struct packing which says

cannot bind packed field ‘ABC.abc::a’ to ‘unsigned int&’

But if I use first type of struct packing then there is no compilation error.

This is my sample code:

//DataStructure.h

#ifndef DATASTRUCTURE_H_
#define DATASTRUCTURE_H_

struct abc
{
    unsigned int a;
    float b;
}__attribute__((packed));

#endif /* DATASTRUCTURE_H_ */



//Main.cpp
#include<iostream>
#include<map>
#include "DataStructure.h"


int main()
{
    struct abc ABC;
    ABC.a=3;
    ABC.b=4.6f;

    std::map<unsigned int,struct abc> Mapp;
    Mapp.insert(std::make_pair(ABC.a,ABC));
}
4

1 回答 1

3

错误来自:

std::make_pair(ABC.a,ABC);

从 C++11 开始,make_pair定义为:

template< class T1, class T2 >
std::pair<V1,V2> make_pair( T1&& t, T2&& u );

所以把它ABC.a作为第一个参数是试图将一个左值引用绑定到一个位域(基本上是一个打包的结构),这是非法的

要解决这个问题,您必须创建一个的unsigned int 并make_pair使用它调用:

unsigned int a = ABC.a;
Mapp.insert(std::make_pair(a,ABC));
于 2018-11-26T13:39:19.533 回答