指针 转 智能指针_智能指针-它们真的那么聪明吗?

指针 转 智能指针

Smart pointers - Are they really that smart?

智能指针-它们真的那么聪明吗?

You might have heard something called smart pointers on your lectures, or that many game companies use them. The reason why just you, should use them might not be clear. Even if you would want to use them you may not know how you do that. The reason why you may not know that, is because the use of templates. Without templates, these smart pointers would actually be more accurate called "dumb pointers." We will cover "dumb pointers" later in our goal to achieve smart pointers.

您可能在您的演讲中听到了称为智能指针的内容,或者许多游戏公司都在使用它们。 只是您应该使用它们的原因可能不清楚。 即使您想使用它们,也可能不知道该怎么做。 您可能不知道这一点的原因是因为使用了模板。 如果没有模板,这些智能指针实际上将更准确地称为“哑指针”。 我们稍后将在实现智能指针的目标中介绍“哑指针”。

What are smart pointers, and what are they good for?

什么是智能指针,它们有什么用?

Smart pointers is basicly your typical object. However, this object is built to be a container of sorts, a container that stores another object of chosen type. This container can then later call upon it's content and all it's member methods and attributes. That gives us the very specific advantage of calling upon the content object deconstructor, meaning removing it from memory automatically.

智能指针基本上是您的典型对象。 但是,此对象被构建为各种容器,该容器存储了所选类型的另一个对象。 然后,此容器可以稍后调用其内容及其所有成员方法和属性。 这给了我们调用内容对象解构函数的非常特殊的优势,这意味着自动将其从内存中删除。

The reason why this are good, is pretty straight forward. To decrease the number of bugs you probably will run into, if you would not to be using it.

之所以如此好,很简单。 如果您不打算使用它,则可以减少可能遇到的错误的数量。

When you create a program, you do not want memory leakage or memory that takes room without reason. Ideally, you want to load your object into memory, and delete it as soon as it is not going to be used again.

创建程序时,您不希望出现内存泄漏或内存无故占用空间的情况。 理想情况下,您要将对象加载到内存中,并在不再使用该对象时立即将其删除。

The most common error, that will happen in your program, will be that you allocate memory, and never release it. When you create a object in the memory (using pointers) you have to delete it. This is sometimes something many programmers forget, not because they are lazy or dumb, but because they say they will get to it later.

在程序中会发生的最常见错误是分配内存,而从不释放内存。 当您在内存中创建对象(使用指针)时,必须将其删除。 有时候,这是许多程序员忘记的事情,不是因为他们懒惰或愚蠢,而是因为他们说以后会使用。

They continue to say that as the code grows, and finally ends up being over 10 000 rows of code. Having bugs appearing with that much code, is to put it mildly, not fun.

他们继续说,随着代码的增长,最终最终超过了10 000行代码。 这么多的代码会出现错误,这是温和的,不是很有趣。

Here comes the smart pointers to rescue. They will automatically when your program shuts down, remove any content you have stored inside it, hence eliminating all sorts of memory leakage.

救援的精明指针到了。 它们会在您的程序关闭时自动删除所有存储在其中的内容,从而消除各种内存泄漏。

How do i get started creating my own class for smart pointers?

我如何开始为智能指针创建自己的类?

This will be divided into two steps, firstly for those of you who do not understand or have used templates in c++ before. This step will be called "dumb pointers." The second step, will be called smart pointers. If you feel that you have good enough knowledge about how to use and create templates, you can jump straight to that step.

这将分为两个步骤,首先是针对那些以前不了解或使用过c ++模板的人。 此步骤称为“哑指针”。 第二步,称为智能指针。 如果您认为自己具有足够的有关如何使用和创建模板的知识,则可以直接跳到该步骤。

Step 1 - Making dumb pointers

第1步-制作哑指针

Imagine the scenario where we have the following class:

想象一下我们有以下课程的场景:

//Player.h - Header file
#pragma once
#include <iostream>

class Player
{
public:
	Player(void);
	void SayHi();
	~Player(void);
};

//Player.cpp - Source file

//Player.cpp-源文件

#include "Player.h"


Player::Player(void)
{
}

void Player::SayHi()
{
	std::cout << "Derp derp" << std::endl;
}


Player::~Player(void)
{
	std::cout << "Master Removed me" << std::endl;
}

and then we have the main.cpp with the following code:

然后我们的main.cpp带有以下代码:

#include <iostream>
#include "auto_ptr.h"
#include "Player.h"

using namespace std;

int main()
{
	Player *dumbpointer = new Player();
	dumbpointer->SayHi();
        //deallocate memory, and set the pointer to null, thanks Sara
        delete dumbpointer;
	dumbpointer = NULL;


	system("pause");
	return 0;
}

What we do here, is to allocate memory dynamicly, by using directive "new". The memory address to this allocation will be stored in our pointer, named "dumbpointer" of our class Player. Now dumbpointer simply points on the dynamicly allocated object, and we can use the operator -> to gain access to it from our code.

我们在这里所做的是通过使用指令“ new”动态分配内存。 此分配的内存地址将存储在我们的指针中,该指针称为类Player的“ dumbpointer”。 现在,dumbpointer只需指向动态分配的对象,我们就可以使用运算符->从我们的代码中访问它。

When we write dumbpointer->SayHi(); the code will look what the dumbpointer points to, and go there to find the function we called. Later we have to call delete dumbpointer, to make sure no memoery leak occurs. That's all it does. It only points. What if pointers could do more? Like noticing when the program exits, and no longer point.

当我们编写dumbpointer-> SayHi();时 该代码将查找哑指针指向的内容,然后去找到我们调用的函数。 稍后,我们必须调用delete dumbpointer,以确保不会发生备忘录泄漏。 这就是全部。 它只是点。 如果指针可以做更多呢? 就像在程序退出时注意,不再指向。

Imagine someone in real life pointing at a house that no longer exists. That would be kind of weird huh? This is when smart pointers comes to the rescue!

想象一下现实生活中有人指向一所不再存在的房屋。 那会有点奇怪吧? 这是聪明的指针来救援的时候!

Step 2 - Making smart pointers

第2步-制作智能指针

When making smart pointers, you have to utilize templates. The reason why, is because you do not know what type of object you want your smart pointer to contain. Up until your first time using templates you always had to declare what type of object you want to use or create. Like a string, int or bool. Template holds whatever type we want, without us having to declare overloads or several attributes that holds that type. You can think that templates are holding types, that are chosen when you compile your code.

制作智能指针时,必须使用模板。 之所以这样,是因为您不知道智能指针要包含哪种类型的对象。 直到您第一次使用模板,您始终必须声明要使用或创建哪种类型的对象。 像字符串一样,int或bool。 模板可以保存我们想要的任何类型,而不必声明重载或保留​​该类型的多个属性。 您可以认为模板是保存类型,这些类型是在编译代码时选择的。

How can I make this smart pointer with template class? Here we only need one thing, a header file called auto_ptr.h

如何使用模板类制作此智能指针? 在这里,我们只需要一件事,即名为auto_ptr.h的头文件

//Tell the compiler that we are making a template class, that can support all kind of types.
//The type we later choose, will be stored in the identifer T.
template <class T> 
class auto_ptr
{
public:
	//explicit = Disable the use of auto_ptr<type> obj = something;
	//Constructor
	explicit auto_ptr(T* pointer) : ptr(pointer){};

	//Deconstructor, will automaticly remove the object from memory when we reach eop (end of program)
	~auto_ptr()
	{
		delete ptr;
	}
	//Link so that when a pointer is used with our auto_ptr, it will be linked to the contained object inside our auto_ptr instead.
	T& operator*()
	{
		return *ptr;
	}
	//When we use the operator -> we want it to return the contained object inside auto_ptr too.
	T* operator->()
	{
		return ptr;
	}
private:
	//Our member attribute, which stores the object we want contained in our auto_ptr
	T* ptr;
};

When we later implement this class in our main.cpp we do like this:

当我们稍后在main.cpp中实现此类时,我们这样做:

#include <iostream>
#include "auto_ptr.h"
#include "Player.h"

using namespace std;

int main()
{
	auto_ptr<Player> smartplayer(new Player);
	smartplayer->SayHi();

	system("pause");
	return 0;
}

What we do here, is to create our smart pointer. By writing <Player>, we tell our template class that T should store the type Player, which is the class we created. This means we can now look at our auto_ptr class, and imagine that instead of writing T in front of our operator overloads, we write Player. This should make everything much more clearer to you. Yes the result from our function will now give back a response that is of the type Player.

我们在这里要做的是创建我们的智能指针。 通过编写<Player>,我们告诉模板类T应该存储Player类型,这是我们创建的类。 这意味着我们现在可以看一下我们的auto_ptr类,并且可以想象,我们不是在运算符重载之前编写T,而是编写Player。 这应该使一切更加清晰。 是的,我们函数的结果现在将返回播放器类型的响应。

Except for how you create this smart pointer, its pretty similar to how you created the dumb pointer. When you call the identifier later, it looks the same as if it would be the dumb pointer. However, as soon as the program closes, the auto_ptr deconstructor will be called and directly remove our Player allocation from memory. This is something the dumb pointer will not, unless we specify it to do so with the directive delete.

除了如何创建此智能指针之外,它与创建哑指针的方式非常相似。 以后调用标识符时,它看起来就像是哑指针。 但是,一旦程序关闭,就会调用auto_ptr解构函数,并直接从内存中删除Player分配。 除非我们使用指令delete进行指定,否则这将是哑指针无法做到的。

Step 3 - Smart pointers and praxis

第3步-智能指针和实践

The above text should make you see the advantages of using smart pointers. However this class is not something you should use in your application. There are already several solutions of smart_pointers out there that will support many many more different solutions and work much better than the above smart pointer class does.

上面的文字应该使您看到使用智能指针的优点。 但是,此类不是您应在应用程序中使用的类。 已经有几种smart_pointers解决方案,它们将支持更多不同的解决方案,并且比上述智能指针类的效果更好。

The new std has a set of these smart pointers. To name a few: std::unique_ptr, std::shared_ptr and std::weak_ptr.

新的std具有一组这些智能指针。 仅举几例:std :: unique_ptr,std :: shared_ptr和std :: weak_ptr。

Although, a open source library that exists today called boost, may be more to your liking.

虽然,如今存在一个称为boost的开源库,但您可能更喜欢。

The boost library has several advantages, and is a library that is used in for instance CryEngine 1,2 and 3.

boost库具有多个优点,并且是一个库,例如在CryEngine 1,2和3中使用。

You can find the boost library here: http://www.boost.org/

您可以在以下位置找到增强库: http : //www.boost.org/

翻译自: https://www.experts-exchange.com/articles/10083/Smart-pointers-Are-they-really-that-smart.html

指针 转 智能指针

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值