www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - enum of struct not calling constructor

reply Andrej Mitrovic <none none.none> writes:
Example 1:

import std.stdio;

enum WindowSizes : QSize
{
    Minimum = QSize(10)
}

struct QSize
{
    int store;
    this(int x)
    {
        store = x + 10;
    }
}

void main()
{
    auto foo = WindowSizes.Minimum;
    assert(foo.store == 10);  // What?

    auto bar = QSize(10);
    assert(bar.store == 20);
}

It appears the constructor is never called for the enum. It does field by field
assignments instead, just take a look at this case:

import std.stdio;

enum WindowSizes : Inverted
{
    Minimum = Inverted(10, 20)
}

struct Inverted
{
    int x;
    int y;
    this(int in_x, int in_y)
    {
        x = in_y;
        y = in_x;
    }
}

void main()
{
    auto foo = WindowSizes.Minimum;
    assert(foo.x == 10);
    assert(foo.y == 20);

    auto bar = Inverted(10, 20);
    assert(bar.x == 20);
    assert(bar.y == 10);
}

As can be seen, this could be a potential source of bugs. Should I file it?
Jan 18 2011
next sibling parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Tuesday, January 18, 2011 08:44:02 Andrej Mitrovic wrote:
 Example 1:
 
 import std.stdio;
 
 enum WindowSizes : QSize
 {
     Minimum = QSize(10)
 }
 
 struct QSize
 {
     int store;
     this(int x)
     {
         store = x + 10;
     }
 }
 
 void main()
 {
     auto foo = WindowSizes.Minimum;
     assert(foo.store == 10);  // What?
 
     auto bar = QSize(10);
     assert(bar.store == 20);
 }
 
 It appears the constructor is never called for the enum. It does field by
 field assignments instead, just take a look at this case:
 
 import std.stdio;
 
 enum WindowSizes : Inverted
 {
     Minimum = Inverted(10, 20)
 }
 
 struct Inverted
 {
     int x;
     int y;
     this(int in_x, int in_y)
     {
         x = in_y;
         y = in_x;
     }
 }
 
 void main()
 {
     auto foo = WindowSizes.Minimum;
     assert(foo.x == 10);
     assert(foo.y == 20);
 
     auto bar = Inverted(10, 20);
     assert(bar.x == 20);
     assert(bar.y == 10);
 }
 
 As can be seen, this could be a potential source of bugs. Should I file it?

Absolutely. - Jonathan M Davis
Jan 18 2011
prev sibling parent Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
http://d.puremagic.com/issues/show_bug.cgi?id=5460
Jan 18 2011