Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating C++/CLI objects without gcnew

Tags:

c++

clr

c++-cli

Is it advisable to create local C++/CLI objects without gcnew? Which of the following creations of string objects str1 and str2 is correct or preferred?

void foo()
{
    System::String str1("string 1");
    System::String^ str2 = gcnew System::String("string 2");

   // Do something with the strings 
}
like image 935
MxNx Avatar asked Dec 04 '25 13:12

MxNx


1 Answers

Creating a reference-type object (ref class) without gcnew is called stack semantics.

It's meant to mirror the plain C++ feature of creating an object on the stack. It also enables RAII: if your object implememnts IDisposable (or in C++/CLI terms if it has a destructor), its Dispose (destructor) method will be called when you leave the scope where it's declared (either normally or through exception propagation). Just like a plain C++ destructor would be called.

Under the hood, the object is created on the managed heap in either case even under stack semantics.

So, there's an obvious benefit of using stack semantics for RAII. If your object is not disposable, you may end up with less cluttered code (you use less ^ characters and use . instead of ->) but it may confuse the reader. It's your call.

like image 183
Lucas Trzesniewski Avatar answered Dec 06 '25 06:12

Lucas Trzesniewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!