何时使用动态内存分配? [英] when to use dynamic memory allocation?

查看:80
本文介绍了何时使用动态内存分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,


我认为动态内存分配应该在一个

事先不知道要分配多少内存时使用运行。 Thinking in C ++中的一个

示例是动态创建一个数组(使用

new),因为在编写程序时,人们不知道它的大小。 br />
但是,在我看来,大小信息必须来自运行时某处的
,并且这些信息可以传递给数组

创建作为一个函数的正式参数。因此,仍然可以使用静态数据创建

数组。方法。这是对的吗?


如果有人可以建议我何时使用动态

内存分配,我会非常感激。

非常感谢!

xian

解决方案

xian_hong2046写道:
< blockquote class =post_quotes>我认为当一个人事先不知道在运行时分配多少内存时,应该使用动态内存分配。


如果您不知道是否需要物品,请使用它,如果

物品的寿命必须持续时间超过创建它的函数。


否则,将对象放在堆栈上。它也动态分配,但

与方法调用同步,所以你不需要明确地删除

的东西。

An
> Thinking in C ++的例子是动态创建一个数组(使用
new),因为在编写程序时不知道它的大小。


这是一个思考C主题,因为像malloc()这样的函数是在C中创建可变大小数组的唯一方法。


读取/加速C ++ /,并使用的std ::矢量<>创建一个变量数组

大小。没有''新''或''删除''。矢量隐藏它们,使你的工作更加轻松,你的代码更安全。

但是,在我看来,尺寸信息必须来自
某处在运行时,这些信息可以作为函数的正式参数传递给数组创建函数。因此,仍然可以使用静态数据来创建
阵列。方法。这是正确的吗?


不,因为C和C ++都使用尽可能接近

金属的低级数组。看看这个功能:


void foo()

{

char slug [99];

...

}


编译器必须在编译时知道foo的大小()

函数的堆栈帧。那就是(在常见的实现中),当foo()启动时,

编译器可以生成最简单和最快的操作码来创建堆栈帧的
。 br />

这就是为什么C ++不允许这样做的原因:


void foo(int amount)

{

char slug [金额];

....

}


''金额' '不是硬常数或编译时间常数。编译器

无法猜测foo的堆栈帧有多大,所以它拒绝生成计算这个大小的较慢的操作码。

C语言通常会让程序员的工作变得更加困难,因此

编译器及其输出代码可以更轻松,更快速地工作。

我真的感谢有人可以建议我何时使用动态内存分配。




这是未编译的代码,可能包含语法错误,但它会得到

你开始了:


typedef std :: auto_ptr< SimCity> SimCityPointer;


SimCityPointer cityFactory(字符串类型)

{

if(" skyscrapers" == type)

返回SimCityPointer(新的SkyScraperCity);


if(ecotopic= = type)

返回SimCityPointer(new EcotopicCity);


if(" shanty" == type)

返回SimCityPointer(新ShantyCity);


返回SimCityPointer (新的NullCity);

}


所有* City类都继承SimCity。


如果用户提供他们想要什么城市的字符串,我们创建一个,然后返回它。


调用函数不关心它是什么样的城市,因此他们不能自己创造它们。如果他们可以,他们可能会把它放在堆栈上,而不是使用''new''



因为这个功能将城市创建系统与其他

功能,它必须安全地调用''new'',然后确保使用

的城市功能确实会在其上调用''删除''他们已经完成了它。


当你打电话给''新'时,你应该立即提供''删除''。在写完更多客户端

函数之后,不要将

关闭或尝试记住,写下删除。我通过将

指针放在模板std :: auto_ptr<>中来提供删除。


丢弃任何没有讨论的C ++教程智能指针!


-

Phlip
http://www.greencheese.org/ZeekLand < - 不是博客!!!


Hi Phlip ,


非常感谢您的详细解释,这真的有帮助!


xian

< br>

在文章< 11 ********************** @ e56g2000cwe.googlegroups .com> ;,

" ; XI *********** @ hotmail.com" < XI *********** @ hotmail.com>写道:

你好,

我认为当一个人事先不知道多少内存时,应该使用动态内存分配分配到运行时间。 Thinking in C ++的一个例子是动态创建一个数组(使用
new),因为在编写程序时,人们不知道它的大小。


这些问题在标准库中得到解决。如果你不知道你需要多少个物品直到运行时间,请使用容器。

如果有人可以告诉我什么时候使用,我真的很感激动态内存分配。




你不应该直接使用动态内存分配

* type *您正在创建的对象直到运行时。

-

魔术取决于传统和信仰。它不欢迎观察,

也不会通过实验获利。另一方面,科学的经验基于
;它可以通过观察和实验进行校正。


Hello,

I think dynamic memory allocation is supposed to be used when one
doesn''t know in advance how much memory to allocate until run time. An
example from Thinking in C++ is to dynamically create an array (using
"new") since one doesn''t know it size when writing the program.
However, it looks to me that the size information must come from
somewhere at run time, and this information can be passed to array
creation function as a function''s formal argument. Therefore, the
array can still be created using a "static" method. Is this right?

I''d really appreciate it if someone could advise me when to use dynamic
memory allocation.

Many thanks!
xian

解决方案

xian_hong2046 wrote:

I think dynamic memory allocation is supposed to be used when one
doesn''t know in advance how much memory to allocate until run time.
Use it if you don''t know if you will need an object or not, and if the
object''s lifespan must last longer than the function that creates it.

Otherwise, put the object on the stack. It also dynamically allocates, but
synchronized with method calls so you don''t need to explicitely delete
things.
An
example from Thinking in C++ is to dynamically create an array (using
"new") since one doesn''t know it size when writing the program.
That is a "Thinking in C" topic, because functions like malloc() are the
only way to create a variable-size array in C.

Read /Accelerated C++/, and use std::vector<> to create an array of variable
size. No ''new'' or ''delete''. The vector hides them, making your job much
easier and your code much safer.
However, it looks to me that the size information must come from
somewhere at run time, and this information can be passed to array
creation function as a function''s formal argument. Therefore, the
array can still be created using a "static" method. Is this right?
No, because both C and C++ use low-level arrays that are as close to the
metal as possible. Look at this function:

void foo()
{
char slug[99];
...
}

The compiler must know, at compile time, how big to make the foo()
function''s stack frame. That''s so that (on common implementations) the
compiler can generate the simplest and fastest possible opcodes to create
that stack frame, when foo() starts.

That''s why C++ should not permit this:

void foo(int amount)
{
char slug[amount];
....
}

''amount'' is not a "hard constant", or "compile time constant". The compiler
cannot guess how big foo''s stack frame will be, so it refuses to generate
slower opcodes that calculate this size.

The C languages often make the programmer work a little harder so the
compiler and its output code can work easier and faster.
I''d really appreciate it if someone could advise me when to use dynamic
memory allocation.



This is uncompiled code that might contain syntax errors, but it will get
you started:

typedef std::auto_ptr<SimCity> SimCityPointer;

SimCityPointer cityFactory(string type)
{
if ("skyscrapers" == type)
return SimCityPointer(new SkyScraperCity);

if ("ecotopic" == type)
return SimCityPointer(new EcotopicCity);

if ("shanty" == type)
return SimCityPointer(new ShantyCity);

return SimCityPointer(new NullCity);
}

All the *City classes inherit SimCity.

If the user provides a string for what city they want, we create one and
return it.

The calling functions don''t care what kind of city it is, hence they can''t
create it themselves. If they could, they might put it on the stack, and not
use ''new''.

Because this function decouples the city creation system from the other
functions, it must safely call ''new'', and then ensure that functions who use
the city will indeed call ''delete'' on it when they are finished with it.

When you call ''new'', you should immediately provide a ''delete''. Don''t put
that off or try to remember, later after you write many more client
functions, to write a ''delete''. I provided for a delete by putting the
pointer inside the template std::auto_ptr<>.

Discard any C++ tutorial that doesn''t discuss smart pointers!

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!


Hi Phlip,

Many thanks for your detailed explanation, that really helped!

xian


In article <11**********************@e56g2000cwe.googlegroups .com>,
"xi***********@hotmail.com" <xi***********@hotmail.com> wrote:

Hello,

I think dynamic memory allocation is supposed to be used when one
doesn''t know in advance how much memory to allocate until run time. An
example from Thinking in C++ is to dynamically create an array (using
"new") since one doesn''t know it size when writing the program.
Those kinds of issues are addressed in the standard library. If you
don''t know how many objects you need until runtime, use a container.
I''d really appreciate it if someone could advise me when to use dynamic
memory allocation.



You should use dynamic memory allocation directly when you don''t know
the *type* of the object you are creating until runtime.
--
Magic depends on tradition and belief. It does not welcome observation,
nor does it profit by experiment. On the other hand, science is based
on experience; it is open to correction by observation and experiment.


这篇关于何时使用动态内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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