C language Smart pointer with complete sample code

Source: Internet
Author: User

Yes, you did not read it correctly.

Not C + + is not C #,

That's the C language you know.

For a long time, C's memory management problem,

Endless, not the time to write a very laborious,

is the difficulty of troubleshooting a memory leak,

Especially in the multi-threaded environment, it is even more difficult,

Such a chronic problem.

C + + uses its RAII mechanism to properly affect a generation of programmers.

Raii probably introduced, do not do science,

There is a need for students, Baidu a bit to understand the details.

What is Raii

The resource acquisition is initialized (Resource acquisition is initialization, RAII), and RAII is a resource management mechanism, and the resource's validity period is tightly bound to the life of the object holding the resource, that is, the object's constructor completes the allocation of resources, To complete the release of resources by the destructor, summarize the sentence is to use objects to manage resources

RAII Implementation principle

When an object is freed from the scope, it calls the destructor of the object class, which is automatically managed and does not need to be called manually. So we can encapsulate the resource into the inside of the class, initialize the object when the resource is needed, and the resource will be freed when the object is released.

When you write for years C code, you are so eager to have such a thing to give you.

In the end, GCC compiler opened a comparisonof, left a backdoor for the benefit of C programmers.

For details, see:

Https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html

Mainly look at this:

Cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can is applied to auto function scope variables; It may is applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.

If-fexceptions is enabled, then cleanup_function are run during the stack unwinding that happens during the processing of The exception. Note that the cleanup attribute does isn't allow the exception-be-caught, only-to-perform an action. It is undefined what happens if Cleanup_function does not return normally.

This cleanup mechanism, which is used, is properly a C destructor.

There is no need to build wheels, the wheels have been built.

LIBCSPTR provides the encapsulation of common smart pointers,

Unique_ptr, shared_ptr, is definitely enough.

Project Address:

Https://github.com/Snaipe/libcsptr

It took a little time to write sample code for the benefit of everyone.

Solve the VS compilation problem.

In addition, VS is not gcc, there is no cleanup to implement this function.

However, you can compile by installing LLVM in VS and choosing LLVM compilation.

To https://llvm.org/releases/download.html

Install after download, and then start vs to see the compiler options.

Put a picture on it, please refer to it.

After you choose, you can play some clang features.

Complete Sample code:

#include <stdio.h>#include"Csptr_smart_ptr.h"structBufferbody {Char*buffer; size_t size;};Static voidCallback_dtor (void*ptr,void*Meta) {    (void) meta; structBufferbody *ctx =ptr; if(Ctx->buffer! =NULL) Free(ctx->buffer);}structBufferbody *write_buffer (Const Char*bufbody, size_t Init_body_len) {SmartstructBufferbody *ctx = shared_ptr (structBufferbody, {0}, Callback_dtor); if(!CTX)//failure to allocate        returnNULL;//Nothing happens, destructor are not called    if(Ctx->buffer = =NULL) {CTX->buffer =malloc(Init_body_len); if(Ctx->buffer! =NULL) CTX->size =Init_body_len; } Else {        if(Ctx->size <Init_body_len) {CTX->buffer =realloc(ctx->buffer, Init_body_len); if(Ctx->buffer! =NULL) CTX->size =Init_body_len; }} size_t Buflen=strlen (bufbody); if(Ctx->size >buflen) memcpy (CTX-buffer, bufbody, buflen); returnSref (CTX);//a new reference on Bufctx are returned, it does not get destoyed}voiddo_something (size_t init_body_len) {SmartstructBufferbody *ctx = Write_buffer ("Hello smart ptr.", Init_body_len); printf ("%s \ n", ctx->buffer); //CTX is destroyed here}intMainvoid) {printf ("Smart Pointers for the (GNU) c\n"); printf ("blog:http://cpuimage.cnblogs.com/\n"); printf ("Tips:u can use LLVM to compile in Visual Studio"); printf ("Download llvm:http://releases.llvm.org/download.html"); //Some_int is an unique_ptr to an int. with a value of 1.Smartint*some_int = Unique_ptr (int,1); printf ("%p =%d\n", Some_int, *some_int); size_t Init_body_len=4096;    Do_something (Init_body_len); //Some_int is destroyed here    return 0;}

Very simple, code rigor do not delve into, we look at the example of the specific use of it.

I think it's a little superfluous to write notes simply.

Because the original project file is very much, compile is very troublesome.

Just a simple modification of the fencing,

The main is to combine the code into a file csptr_smart_ptr.h, with sample code, clean and portable.

Corresponding Project address:

Https://github.com/cpuimage/libcsptr

Can only say, with it, you can save a lot of C memory management heart.

Of course there will be many people who question whether there will be big pits,

Maybe there is, maybe not, but the C smart pointer does.

I believe the truth, of course, the fact that the compiler provides a way for you,

However, some people may indeed say that they do not believe in compilers,

Well, that's right, I don't believe it either.

But, no doubt, everyone is using it, although they don't believe it.

The mouth says that, the body is still very honest.

Above, right when a.

It's better to have fun together than to play alone.

If you have other related questions or needs, you can contact me to discuss the email.

e-mail address is:
[Email protected]

C language Smart pointer with complete sample code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.