Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What speaks against doing this?:

public struct T
{
    private float[] Elements { get; set; }

    public T(params float[] elements)
    {
        Elements = elements;
    }
}

Could this possibly lead to undefined behaviour? Or will the garbage collector keep the array alive since it is beeing used?

question from:https://stackoverflow.com/questions/66048594/c-assign-array-with-params-argument

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
489 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just to provide an answer and add some details.

This is perfectly legal. The compiler will in effect transform

new T(1, 2, 3)

To

new T(new float[]{1, 2, 3})

Since arrays are reference types the constructor will just assign a reference. And since references are tracked by the garbage collector there is no risk for a memory leak or other issues that may affect c++.

From the language specification (Emphasis mine)

Within a method that uses a parameter array, the parameter array behaves exactly like a regular parameter of an array type. However, in an invocation of a method with a parameter array, it is possible to pass either a single argument of the parameter array type or any number of arguments of the element type of the parameter array. In the latter case, an array instance is automatically created and initialized with the given arguments.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...