如何返回对方法中创建的对象的引用 [英] How to return references to object created inside a method

查看:103
本文介绍了如何返回对方法中创建的对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我推测返回对方法中创建的对象的引用的最佳方法,如下面的情况:

  class A {
public:
A(){}
〜A(){}
}

class Foo {
public:
Foo(){}
〜Foo(){}
A& create(int random_arg){
//创建对象A并返回其引用
}
};

void other_method(){
Foo f;
A a = f.create();
//用
执行操作{

我考虑了三种可能的解决方案:


  1. 创建原始指针并返回引用,但这是不好的,因为不能保证对象将正确已删除:

      create(int random_arg){
    A * a = new A();
    return * a;
    }


  2. 创建shared_ptr并返回shared_ptr的值。这样,shared_ptr将负责删除对象:

      shared_ptr< A> create(int random_arg){
    boost :: shared_ptr< A> a_ptr(new A());
    return a_ptr;
    }


  3. 创建一个shared_ptr并返回一个引用:

      A& create(int random_arg){
    boost :: shared_ptr< A> a_ptr(new A());
    return * a_ptr;
    }


是最常用的,但是在这种方式下,我必须在应用程序中传播shared_ptr,我宁愿有引用,或者更好的 const 引用。



你认为处理这种情况的最好办法是什么?有没有其他可能性我没有考虑过?

解决方案

不要这样做。



只需返回 A 这可能是编译器会 隐含的对象副本。但您可以保证不会通过为 A 编写 move constructor

>

I am reasoning about the best approach to return references to objects created inside a method, like in the following situation:

class A{
public:
    A(){}
    ~A(){}
};

class Foo{
public:
    Foo(){}
    ~Foo(){}
    A& create(int random_arg){
         // create object A and return its reference
    }
};

void other_method(){
     Foo f;
     A a = f.create();
     // do stuff with a
{

I have considered three possible solutions:

  1. create a raw pointer and return a reference, but this is bad because there is no guarantee that the object will be properly deleted:

    A& create(int random_arg){
         A* a = new A();
         return *a;
    }
    

  2. create a shared_ptr and return the shared_ptr by value. In this way the shared_ptr will take care of the object deletion:

    shared_ptr<A> create(int random_arg){
         boost::shared_ptr<A> a_ptr(new A());
         return a_ptr;
    }
    

  3. create a shared_ptr and return a reference:

    A& create(int random_arg){
         boost::shared_ptr<A> a_ptr(new A());
         return *a_ptr;
    }
    

The second solution seems to be the most used, but in this way I have to spread shared_ptr in the application and I would prefer to have references, or better const references.

What do you think is the best way to handle this situation? Are there other possibilities I have not considered?

解决方案

Don't do this. You're most likely to have a dangling reference.

Just return the instance of A by value instead.

It's likely that the compiler will elide the implied object copy. But you can guarantee that an object copy will not be made by writing a move constructor for A.

这篇关于如何返回对方法中创建的对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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