局部变量或指针 [英] Local variable or a pointer

查看:83
本文介绍了局部变量或指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何随机C ++框架中给定一个类,你如何知道是否必须在堆栈上创建一个简单的对象或者指向堆上的对象?

Given a class in a any random C++ framework, how do you know if you have to create a simple object on stack or a pointer to an object on heap?

假设一个以引用(&)变量形式接受参数的函数。调用者可以向它传递一个局部变量或一个指针(* ptr)。被调用的函数可以或不可以从传递的对象复制dat。

Assume a function which accepts argument in the form of a reference(&) variable. The caller can pass a local variable to it or a pointer too(*ptr). The called function may or may not copy dat from the passed object.

这个问题是我的以前的问题与C ++ Bada开发相关。

This question is a followup of my previous question related to C++ Bada development.

推荐答案

一般来说,每个精心设计的C ++库都将允许两者。在大多数情况下,库不在乎调用者分配内存的位置,因为调用者处理自己的内存。如果库有额外的要求(例如它占用了指针),那么它会仔细地记录这个。

In general, every well-designed C++ library will allow both. In most cases the library doesn’t care where the caller allocates memory, since the caller handles its own memory. If the library has additional requirements (e.g. that it takes over possession of a pointer) then it will carefully document this.

此外,作为一般指导,指针和freestore内存。 C ++设计时考虑了堆栈对象。如果没有令人信服的理由使用不同的东西,那么不要。 new 应该只在您的代码中使用非常谨慎,并且 delete 应该从不使用 - 也就是说,总是让你分配的内存以自动方式处理(智能指针)。

Furthermore, as a general guideline, avoid pointers and freestore memory. C++ is designed with stack objects in mind. If there is no compelling reason to use something different, then don’t. new should be used only very sparingly in your code, and delete should never be used – that is, always let your allocated memory be handled in an automatic fashion (smart pointers).

这篇关于局部变量或指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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