2014-12-15 17 views
8

Io uso g ++ per compilare il codice con i campi compressi. Tuttavia, ricevo un errore quando tento di restituire un riferimento a un campo compresso.Perché non posso restituire un riferimento a un campo compresso?

Esempio:

struct __attribute__((packed)) Foo { 
    int* ptr; 
    uint16_t foo; 
    int*& getPtr(){ 
     return ptr; 
    } 
}; 

cede errore:

test.cpp:22:14: error: cannot bind packed field ‘((Foo*)this)->Foo::ptr’ to ‘int*&’ 
    return ptr; 

Perché non è possibile restituire un riferimento a un campo imballato?

+6

Se è pieno, il campo potrebbe non essere allineato correttamente. –

+0

@ T.C .: C'è un modo per dire a gcc "Allineamento vite, sono su x86"? – gexicide

+1

@gexicide 'return (int * &)ptr;' –

risposta

2

C'è un rapporto gcc bug Cannot bind packed field che copre questo e dice:

The C++ spec (C++03, Sects. 3.9, 3.9.1, 3.9.2) are very clear that T and "pointer to T" have implementation-specific alignment requirements. If you have a "pointer to T" then you may assume that it meets the alignment requirements. I'm sure the C spec has similar language.

In the OP's case, the following code could violate the alignment requirements

Essi suggeriscono una soluzione mediante l'attributo alignment per definire il proprio tipo di allineamento, ma non sembra come esso funziona.

+0

Non crederci, ho appena trovato la stessa segnalazione di bug e stavo per pubblicare la stessa citazione ... – Columbo

+0

Ho provato la soluzione alternativa con l'attributo alginment. my gcc. – gexicide

+0

@gexicide Il "workaround" sembra un hack che evita il messaggio di errore ma in realtà non funziona Avere 'getPtr' restituire invece un proxy. –

Problemi correlati