The syntax for stack versus heap allocation of C++, C++/CLI and CSharp

來源:互聯網
上載者:User

 

The syntax for stack versus heap allocation of C++, C++/CLI and CSharp

Native C++ lets you choose where to create a given object.Any type can be allocated on the stack or the CRT heap.

// allocated on the stack

std::wstring stackObject;

// allocated on the CRT heap

std::wstring* heapObject = new std::wstring;

As you can see, the choice of where to allocate the objectis independent of the type, and is totally in the hands of the programmer. Inaddition, the syntax for stack versus heap allocation is distinctive.

 

C#, on the other hand, lets you create value types on thestack and reference types on the heap. The System.DateTime type, used in thenext few examples, is declared a value type by its author.

// allocated on the stack

System.DateTime stackObject = new System.DateTime(2003, 1,18);

// allocated on the managed heap

System.IO.MemoryStream heapObject = new System.IO.MemoryStream();

As you can see, nothing about the way you declare the object gives any hint at whether the object is on the stack or the heap. That choiceis left completely up to the type's author and the runtime.

 

C++/CLI's way (distinctive):

// allocated on the stack

DateTime stackObject(2003, 1, 18);

// allocated on the managed heap

IO::MemoryStream^ heapObject = gcnew IO::MemoryStream;

Again, there is nothing surprising about the declaration of the value type. The reference type, however, is distinctive. The ^ operatordeclares the variable as a handle to a CLR reference type. Handles track,meaning the handle's value is automatically updated by the garbage collector asthe object to which it refers, is moved in memory. In addition, they are rebindable, which allows them to point to a different object, just like a C++pointer. The other thing you should notice is the gcnew operator that is used in place of the new operator. This clearly indicates that the object is being allocated on the managed heap. The new operator is no longer overloaded (no punintended) for managed types, and will only allocate objects on the CRT heap,unless of course you provide your own operator new. Don't you just love C++!

That is object construction in a nutshell: Native C++pointers are clearly distinguished from CLR object references.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.