What is the difference between the following two code snippets?
public void foo(out classA x)
{
y = new classA();
x = y;
}
and the second:
public void foo(out classA x)
{
classA y;
x = y;
}
Is it true that the second snippet is dangerous, because x
has now a reference to this local y
, which might be already dea开发者_运维知识库d after exiting foo
?
Why do we have to use "new" in general?
I'm a bit confused, because in C++, if x
in the second snippet would be a pointer, the statement x = y
would not even compile since y
is not a pointer.
Let's assume for a moment that the second snippet is
public void foo(out classA x)
{
classA y = new classA();
x = y;
}
The snippet as you wrote it does not compile in C# at all. y
has to be assigned first. The line classA y;
does not create an instance of classA
on the stack as it would in C++. It simply declares a variable y
of type classA
.
With the compiling snippet in mind, assigning an out
variable to a locally declared and initialized object is not dangerous in any way. The classA
object that y
points to and that is assigned to x
will remain alive and well until x
goes out of scope wherever it's declared/used.
Your confusion, I think, is that in C++ the second example would return a reference to a stack-allocated object. That doesn't happen in C#.
Given your second example in C#:
public void foo(out classA x)
{
classA y; // Doesn't allocate an object
x = y;
}
This probably won't compile, anyway, because y
is never assigned a value.
Is it true that the second snippet is dangerous [...]
Not in C#; you're thinking of native languages like C or C++ that allow one to take a pointer to a local variable. In C#, everything (within reason) is a reference to a managed object. Everything is essentially on the heap.
It is not dangerous because the code will NOT be able to be compiled unless all "out" parameters are given a definition before the method returns or exits.
精彩评论