如何延长局部变量的生命周期或使用引用的正确方法

Ego*_*lev 8 c++ reference move object-lifetime c++11

我正在开发一些课程,并提出了这个问题.考虑我有以下课程:

struct A
{
    int *p;
    A() 
    {
        p = new int(1); 
        cout << "ctor A" << endl; 
    }
    A(const A& o) 
    { 
        cout << "copy A" << endl;
        p = new int(*(o.p));
    }
    A(A&& o) 
    {
        cout << "move A" << endl;
        p = std::move(o.p);
        o.p = NULL;
    }
    A& operator=(const A& other)
    {       
        if (p != NULL)
        {
            delete p;
        }
        p = new int(*other.p);
        cout << "copy= A" << endl;
        return *this;
    }
    A& operator=(A&& other)
    {       
        p = std::move(other.p);
        other.p = NULL;
        cout << "move= A" << endl;
        return *this;
    }
    ~A()
    {
        if(p!=NULL)
            delete p;
        p = NULL;
        cout << "dtor A" << endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

以下A作为属性的类:

class B {
public:
  B(){}
  A myList;
  const A& getList() { return myList; };
};
Run Code Online (Sandbox Code Playgroud)

此函数检查一些变量值并在不同情况下返回不同的对象:

B temp;
A foo(bool f)
{
    A a;
    *a.p = 125; 
    if (f)
        return a;
    else
    {
        return temp.getList();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我想要像这样使用这个函数:

A list1 = foo(true);
if(list1.p != NULL)
    cout << (*list1.p) << endl;

cout << "------"<<endl;
A list2 = foo(false);
if (list2.p != NULL)
    cout << (*list2.p) << endl;
Run Code Online (Sandbox Code Playgroud)

这种情况的目的是:

函数foo应该返回(或移动)而不复制一些本地对象,p如果参数是变化的true,或者应该返回全局变量的属性temp而不调用复制构造函数A(即返回引用myList)并且它也不应该myList从中获取B(它不应该myListB,所以std::move不能使用)如果参数是false.

我的问题是:

我应该如何改变功能foo以遵循上限条件?当前实现的foo工作正好true以及移动该局部变量,但是如果false它调用复制构造函数list2.其他想法是以某种方式延长局部变量的生命周期,但添加const引用对我来说不起作用.目前的输出是:

ctor A
ctor A
move A
dtor A
125
------
ctor A
copy A
dtor A
1
dtor A
dtor A
dtor A
Run Code Online (Sandbox Code Playgroud)

Jar*_*d42 4

如果你可以更改B

class B {
public:
  B(){}
  std::shared_ptr<A> myList = std::make_shared<A>();
  const std::shared_ptr<A>& getList() const { return myList; };
};
Run Code Online (Sandbox Code Playgroud)

那么foo可以是:

B b;
std::shared_ptr<A> foo(bool cond)
{
    if (cond) {
        auto a = std::make_shared<A>();
        *a->p = 125; 

        return a;
    } else {
        return b.getList();
    }
}
Run Code Online (Sandbox Code Playgroud)

演示

输出是

ctor A
ctor A
125
------
1
dtor A
dtor A
Run Code Online (Sandbox Code Playgroud)