D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 19885 - possibility to skip required initialization in constructor using ref parameter
Summary: possibility to skip required initialization in constructor using ref parameter
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86_64 Linux
: P1 regression
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2019-05-18 17:57 UTC by dayllenger
Modified: 2021-10-28 15:31 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description dayllenger 2019-05-18 17:57:35 UTC
This code compiles (since 2.081.2), but shouldn't:

struct A
{
    @disable this();
    this(int) {}
}

struct B
{
    A a;
    this(int)
    {
        f(a);
    }
}

void f(ref A a) {}

void main()
{
    B b = B(1);
}

The `a` must be constructed in the `B` constructor. But if we pass it somewhere via ref parameter, compiler ignores `a` and leaves it in default state.

By the way, if we change ref to out, then there is normal `Error: cannot have out parameter of type A because the default construction is disabled`.
Comment 1 RazvanN 2021-02-18 12:09:27 UTC
I think that the behavior was designed to allow for:

initializeA(ref A a)
{
    a = A(2);
}

struct B
{
    A a;
    this(int)
    {
        initializeA(a);
    }
}

This is a common pattern and forbidding this might brake a lot of code. However, there is no way the compiler can know if the function actually initializes a or not.

The problem with `out` is slightly different. Since A does not have default construction the parameter cannot be initialized before entering the function.

Also, there is this issue [1], which was fixed by considering that taking the address of a variable in the constructor is the same as initializing it. Passing a field by ref to a function could be seen the same as taking its address, so by those standards this issue would be a WONTFIX. 

[1] https://issues.dlang.org/show_bug.cgi?id=15869