什么时候你想使用指针vs C ++中的值? [英] When do you want to use pointers vs values in C++?

查看:151
本文介绍了什么时候你想使用指针vs C ++中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自Java,试图学习C ++。

I'm coming from Java and attempting to learn C++.

据我所知,使用Pointers与Java中的引用变量非常相似,因为您将一个内存地址传递给该值。所以我觉得我已经很好地理解了他们。我还理解这些变量存储在堆上。

As far as I can tell, using Pointers is very similar to how reference variables work in Java, in that you pass a memory address to the value. So I feel like I have gotten a pretty good understanding of them. I also understand that these variables are stored on the heap.

但是,我看到有另一种方法,你可以在C ++中声明变量,没有新的运算符/指针只是做类似的:

However, I see that there is another way in which you can declare variables in C++, without the new operator/pointers simply doing something like:

Employee boss("Frank");

这将创建一个以Frank作为参数的Employee值。这些变量存储在堆栈中。

Which will create a value of Employee with "Frank" as the parameter. These variables are stored on the stack.

所以,你有这两种不同的方式创建变量,并且都有自己独特的行为(还有内存管理) 。

So, you have these 2 very different ways of creating variables and both with their own unique behavior (with memory management as well?).

我的问题是,什么时候适合使用指针VS值?什么是最佳实践?

My question is, when is it appropriate to use pointers VS values? What is the best practice? How should I know in what way I want to declare my variables most of the time?

推荐答案

C ++指针的操作方式与Java对象完全一样,因为它们可能是无效的( NULL ),并且传递给过程很便宜。

C++ pointers operate exactly like Java objects, in that they may be invalid (NULL) and are cheap to pass to procedures.

C ++引用是围绕指针的薄包装。他们不应该是无效的,但在某些情况下可能是。例如,可以从 NULL 指针创建引用,或者引用的内存可能被删除。

C++ references are a thin wrapper around pointers. They're not supposed to be invalid, but in some cases may be. For example, a reference might be created from a NULL pointer, or the memory it references might be deleted.

在代码示例中,您提供:

In the code example you give:

Employee boss("Frank");

您使用的是称为值的东西。与指针和引用不同,值是它们表示的对象,而不是间接。

you are using something called a "value". Unlike pointers and references, values are the object they represent, not an indirection.


我的问题是,是否合适
使用指针VS [值]?
最佳做法是什么?应该如何
我知道在什么方式我要声明
我的变量大多数时间?

My question is, when is it appropriate to use Pointers VS [values]? What is the best practice? How should I know in what way I want to declare my variables most of the time?

C ++没有垃圾回收,因此在变量的作用域有限时使用值。例如,不是为过程中的每个变量分配 new 并为其分配 delete ,您可以分配它们在堆栈上,不担心内存。

C++ doesn't have garbage collection, so values are used when the scope of a variable is limited. For example, instead of allocating one with new and deallocating with delete for every variable in a procedure, you can allocate them on the stack and not worry about the memory.

这篇关于什么时候你想使用指针vs C ++中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆