union member assignment



  • hallo

    union type
    {
      int x;
      float y;
    };
    
    int main()
    {
      type val;
      val.x = 1;
    
    //sicher ok:
      float tmp = static_cast<float>( val.x );
      val.y = tmp;
    
    //auch ok, oder eine schlechte idee?
      val.y = static_cast<float>( val.x );
    }
    

    ty, bb



  • unskilled schrieb:

    h val.y = tmp;

    //auch ok, oder eine schlechte idee?
    val.y = static_cast<float>( val.x );

    Nicht ok. Das ist undefiniert.

    Bei union gibt es maximal einen aktiven Member (der, dem zuletzt etwas zugewiesen wurde) und nur dieser darf gelesen werden. Die anderen Member zu lesen führt zu undefiniertem Verhalten.


  • Mod

    Die anderen Member zu lesen führt zu undefiniertem Verhalten

    Wir lesen nur einen Member.



  • Arcoth schrieb:

    Die anderen Member zu lesen führt zu undefiniertem Verhalten

    Wir lesen nur einen Member.

    Was ist an meinem Satz in diesem Zusammenhang missverständlich?


  • Mod

    AFAICS ist es leider nicht definiert:

    [expr.ass]/8 schrieb:

    If the value being stored in an object is accessed from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have the same type, otherwise the behavior is undefined.

    Hier ist eine Notiz aus DR #556:

    Instead of being a general statement about aliasing, it's describing the situation in which the source of the value being assigned is storage that overlaps the storage of the target object.

    Andererseits führt static_cast eine Temporäre Variable ein:

    An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary
    variable as the result of the conversion.

    Diese temporäre Variable wäre natürlich völlig unabhängig von diesem Unionobjekt..

    Was ist an meinem Satz in diesem Zusammenhang missverständlich?

    Entweder der Satz ist einfach total zusammenhangslos von dir reingeworfen worden, oder er hält als Begründung für den ersten her, und den Fall habe ich angenommen.



  • @tybb natürlich ist die zweite variante eine alternative zur ersten. offenbar war das doof geschrieben, deshalb wohl deine antwort

    @arcoth: danke; dann werd ichs wohl doch mit der temporären variable machen. wird schon wegoptimiert werden, wenns nicht nötig ist.

    bb


Anmelden zum Antworten