分享
 
 
 

Using managed reference types in C++

王朝c/c++·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

Using managed reference types in C++

By Chris Maunder

A quick introduction to using .NET managed reference types in C++

IntroductionOne of the nice things about .NET are the common base classes. These classes are essentially the API of .NET, and are available from all languages equally. Once you know how to use a String in VB.NET you also know how to use it in C# and C++. Once you have struggled up the learning curve for one language you can then go on to use that knowledge in other .NET languages.

In .NET there are value types and reference types. Value types refer to simple data structures such as int's and enumerations, and are stored on the stack. Reference types are created on the .NET managed heap, which allows the garbage collector to track their lifetime and free instances when they are no longer required.

Think of a reference type as a pointer - though not in the traditional C/C++ sense of the word. The actual location of a variable on the managed heap will change as the garbage collector recovers unused memory and compacts the heap, so in a short time a traditional pointer to a spot on the heap will be invalid. A .NET reference, on the other hand, will always give you access to your values no matter where it has been moved on the heap. A variable of reference type will always either contain a reference to a value of that type, or null. Assigning the value of a reference variable to another variable copies the reference, not the value stored. Be warned!

Value types are stored on the stack and are accessed directly. Once the memory containing that value is freed, the value type instance is destroyed. Hence, references to value types are not allowed. If it were allowed it would be possible to have a reference point to an invalid memory location. A value type will always point to a variable of that type, and cannot be null. Assigning a value type to another variable results in a copy of the value being made.

Creating an instance of a reference typeValue types are easy since they are declared on the stack. It would be insane if you had to call new each time you wanted to create an int or double. Reference types are a little more complicated in that they cannot be created on the stack.

Reference types are created on the .NET managed heap, and so must be created using the overloaded new operator. The new operator for managed types not only creates the object on the managed heap, but also initialises the value of the variable to 0. The value passed back from new will not be a .NET reference, and not pointer in the traditional sense. In the following examples we will concentrate on the String class. You'll use it a lot, and it has some tricks up its sleave.

To create an instance of a reference type you simply declare a pointer of the variables type and create the object using new.

String* s = new String("This is a string");

Attempting to declare a managed object on the stack simply won't work:

String s = "This is a string"; // WILL NOT COMPILE

The String class' constructor contains many different overrides for many different occasions, but does not contain an override for String().

Other ways of declaring a String are as follows:

String* s = new String("This is an ANSI string");

String* s = "This is an ANSI string";

String* s = L"This is a UNICODE string";

String* s = S"This is a .NET string";

ANSI and UNICODE strings should be familiar to you. .NET strings (those prefixed by 'S') are new and offer better performance than standard C++ literal strings. As well as this, all instances of identical string literals actually point to the same string. If s1 and s2 are two String's, then the following code:

s1 = S"This is a .NET string";

s2 = S"This is a .NET string";

if (s1 == s2)

printf("s1 == s2\n");

else

printf("s1 != s2\n");

s1 = "This is a C++ literal string";

s2 = "This is a C++ literal string";

if (s1 == s2)

printf("s1 == s2\n");

else

printf("s1 != s2\n");

would produce

s1 == s2

s1 != s2

Note that C++ literal strings can be used where ever .NET strings are used, but .NET strings cannot be used where C++ strings are expected.

Note also the use of printf in the above snippet. Just because we are using .NET types and methods doesn't mean we lose our standard non-managed libraries. In managed C++ we get the best of both worlds.

Creating your own managed typesCreating your own managed types is achieved using the new __gc keyword.

__gc class MyClass

{

public:

int ID;

};

You then use this class as you would any other managed class:

MyClass* mc = new MyClass;

mc->ID = 5;

Because mc is a managed type it will be automatically initialised to 0 (ie mc->ID will be set as 0).

Using managed types in non-managed functionsThe final point is that when combining managed and unmanaged code you will invariably come across situations where you need to pass a managed pointer to a function expecting an unmanaged (fixed) pointer.

To allow this, a new keyword __pin has been introduced that essentially pins down the managed pointer so that the garbage collector will not move it.

MyClass __pin* pMC = mc;

printf("The pinned value of mc is %d\n", pMC->ID);

History16 Oct 2001 - updated source files for VS.NET beta 2

About Chris Maunder

Site Admin

Editor

Site Builder

Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs CodeProject. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.

His programming experience includes C/C++, C#, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.

He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.

Chris was born and bred in Australia but is currently based in Toronto enjoying the weather. For relaxation he is into snowboarding, rock climbing, mountain biking, and storm chasing.

Click here to view Chris Maunder's online profile.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有