Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does C++ realize the intelligent pointer outside the standard library?

Shulou Source: shulou.com Published: 2022-06-01 19:26:14 09月28日 Update

This article mainly explains "how C++ can achieve smart pointers outside the standard library". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how C++ can achieve smart pointers outside the standard library.

R.31: if you need to implement smart pointers other than the standard library, follow the basic pattern in the standard library

Reason (reason)

The guidelines in later chapters also apply to other types of third-party and custom smart pointers, which are effective in finding general smart pointer errors that can cause performance and correctness problems. What you need is a rule that works for all smart pointers.

Any type that overloads unary * and-> (including major templates and specializations) can be considered a smart pointer.

If it is copiable, it is considered a shared pointer with a reference count.

If it is not copiable, it is considered an exclusive unique_ptr.

Example (sample)

/ / use Boost's intrusive_ptr

# include

Void f (boost::intrusive_ptr p) / / error under rule 'sharedptrparam'

{

P-> foo ()

}

/ / use Microsoft's CComPtr

# include

Void f (CComPtr p) / / error under rule 'sharedptrparam'

{

P-> foo ()

}

In both cases, a mistake was made in the sharedptrParam guidelines: P is a shared pointer, but nothing about sharing is used here. And passing smart pointers by value is a default permission; this function should accept smart pointers only when participating in the lifecycle management of widget. Other cases: if functions are allowed to be null, they should accept widget*, otherwise they should accept widget&. These smart pointers match the concept of Shared_pointer, so the rules recommended by these guidelines can also be applied to them immediately.

At this point, I believe you have a deeper understanding of "how C++ can achieve smart pointers outside the standard library". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Pointers intelligence standards guidelines Clearing valid content function situation copy type error learning recommendation practical deeper interest function reason cycle Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Linux MySQL Docker Shulou Information