返回智能指针时的最佳实践 [英] best practice when returning smart pointers

查看:484
本文介绍了返回智能指针时的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回一个智能指针,例如当一个boost :: shared_ptr的什么是最好的做法?我用标准应该返回的智能指针,或底层的原始指针?我来自C#,所以我倾向于总是返回智能指针,因为这感觉不错。像这样(跳过常量,正确性缩短code):

What is the best practice when returning a smart pointer, for example a boost::shared_ptr? Should I by standard return the smart pointer, or the underlying raw pointer? I come from C# so I tend to always return smart pointers, because it feels right. Like this (skipping const-correctness for shorter code):

class X
{
public:
    boost::shared_ptr<Y> getInternal() {return m_internal;}

private:
    boost::shared_ptr<Y> m_internal;
}

不过,我已经看到了一些有经验的codeRS返回原始指针,并把原始指针的载体。什么是做正确的方式?

However I've seen some experienced coders returning the raw pointer, and putting the raw pointers in vectors. What is the right way to do it?

推荐答案

有没有正确的方式。这真的取决于上下文。

There is no "right" way. It really depends on the context.

您可以在内部处理内存智能指针和外部提供参考或原始指针。毕竟,你的界面的用户并不需要知道如何在内部管理内存。在同步情况下,这是安全和有效的。在异步情况下,也有不少缺陷。

You can internally handle memory with a smart pointer and externally give references or raw pointers. After all, the user of your interface doesn't need to know how you manage memory internally. In a synchronous context this is safe and efficient. In an asynchronous context, there are many pitfalls.

如果你不确定该怎么做,你可以智能指针安全返回到您的来电者。当引用计数为零的对象将会被释放。只要确保你没有,保持对象的智能指针永远这样$ P $需要时pventing的释放的一类。

If you're unsure about what to do you can safely return smart pointers to your caller. The object will be deallocated when the references count reaches zero. Just make sure that you don't have a class that keeps smart pointers of objects for ever thus preventing the deallocation when needed.

随着最后一个音符,在C ++中不要过度使用动态分配的对象。有很多情况下,你并不需要一个指针,可以在引用和常量引用工作。这是更安全,减少对内存分配器的pressure。

As a last note, in C++ don't overuse dynamically allocated objects. There are many cases where you don't need a pointer and can work on references and const references. That's safer and reduces the pressure on the memory allocator.

这篇关于返回智能指针时的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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