How would one code the following C# code in Managed C++
void Foo()
{
using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))
{
//do stuff
}
}
Clarificaton: For managed objects.
How would one code the following C# code in Managed C++
void Foo()
{
using (SqlConnection con = new SqlConnection("connectionStringGoesHere"))
{
//do stuff
}
}
Clarificaton: For managed objects.
Assuming you mean C++/CLI (not the old Managed C++), the following are your options:
(1) Mimic a using-Block with using automatic / stackbased objects:
This will call the Destructor of the "conn" Object when the next enclosing block ends. Whether this is the enclosing function, or a block you manually add to limit scope doesn't matter.
(2) Explicitly call "Dispose", i.e. destruct the object:
The first one would be the direct replacement for "using". The second one is an option, typically you won't need to do unless you optionally pass the reference to somewhere else.
If you're concerned about limiting the variable's lifetime rather than automatic disposal, you can always just put it into its own scope:
To to that in Managed C++ just use stack semantics.
When con goes out of scope the "Destructor", ie Dispose(), is called.
You could do something similar in an auto_ptr style:
with the following:
For reference: