清理堆分配对象的良好实践或惯例? [英] Good practice or convention for cleanup heap allocated object?

查看:60
本文介绍了清理堆分配对象的良好实践或惯例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++.我有C,C#,ObjC背景.相当高级的语言.

I am learning C++. I have C, C#, ObjC background. Pretty higher level languages.

在C#或ObjC上,由于函数或方法的结果,它很容易返回堆分配的对象.因为对象的清理是按照惯例进行管理的.它会在适当的时候被销毁.

On C# or ObjC , it's trivial returning heap allocated object as a result of a function or method. Because the cleanup of objects are managed (by convention). It will be destroyed at proper time.

但是我不知道该如何用C ++处理.

But I don't know how should I handle this in C++.

例如

std::string* makeString()
{
    std::string* str = GetSomeStringFromArbitrarySource ();
    SaveSomewhereElseInternally (str);
    return str;
}
void useString ()
{
    std::string* str = makeString ();

    // Where and how should I cleanup the `str` object?
    // It is not safe `delete str` here because it may be used on another place.
}

当堆分配的对象通过许多函数传递时,清理堆分配的对象的推荐的常规方法是什么?

What is the recommended and conventional way to cleanup heap allocated object when it is passed over many functions?

我看了几个智能指针,但是它们看上去并没有真正地 reduce 复杂性或需要注意的东西.我会误会智能指针吗?

I looked several smart pointers, but they don't look really reduce complexity or things to care. Am I misunderstanding the smart pointers?

推荐答案

如果可以使用C ++ 11,请使用共享指针.这些指针实现了一种机制,一旦销毁了最后一个指针,便删除分配的对象.如果您使用的是C ++ 03,请使用boost的共享指针.如果您不能使用它们,请尝试将堆分配包装在分配给堆栈的类中,然后将引用传递给周围的类,并提供 RAII Wiki 阅读.

If you can use C++11 use shared pointers. These pointers implement a mechanism to delete the allocated object once the last of them is destroyed. If you are using C++03, use boost's shared pointers. If you can not use either, try to wrap heap allocations in classes you allocate on the stack, then pass references to those around, also give the RAII wiki a read.

这篇关于清理堆分配对象的良好实践或惯例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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