Skip to content

[BUG] Inconsistent Initialization #823

@msadeqhe

Description

@msadeqhe

Description

The result of initialization is surprising because by changing the placement of =, its result can be changed, and no one expects to have a different result from the same (args...) in similar variable declarations.

To Reproduce

For example:

point: type = {
    value: i32;
    operator=: (out this, inout i: std::initializer_list<i32>) = {
        value = std::accumulate(i.begin(), i.end(), 0);
    }
    operator=: (out this, a: i32, b: i32) = {
        value = a * b;
    }
}

var1:   point = (1, 2); // value is 1 + 2 = 3
var2: = point   (1, 2); // value is 1 * 2 = 2

I'm using Cppfront from Compiler Explorer.

I expect the value of both var1 and var2 to be the same. But their value members have different values, var1.value is 3, var2.value is 2. On the other hand, their initializations are so much similar, therefore the result is surprising.

Additional Context

Available solutions:

  • Make the behavior of initializations (in the example) to be the same. Ban the programmer from writing any type that has overloaded constructors with both std::initializer_list<TYPE> and TYPE, ... signatures, because it's considered bad API design. Also find a way to fix bad API design of Cpp1 libraries (such as std::vector) in Cpp2 side too by extending them with new constructors.
  • Treat std::initializer_list<TYPE> as the type of a list literal, and devote a notation such as [] to create an instance of it in the same way that string types have their own string literals with notation "".
  • Allow the programmer to call the constructor with either () (direct initialization) or [] (list initialization), and make them to fall back to each other in generic code.

Also discussion #637 and issue #193 are related to this bug. Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions