c++ - 如何延长局部变量的生命周期或使用引用的正确方法是什么

标签 c++ c++11 reference move object-lifetime

我正在开发一些类(class)并遇到了这个问题。 考虑我有以下类(class):

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;
    }
};

下面的类有A作为属性(property):

class B {
public:
  B(){}
  A myList;
  const A& getList() { return myList; };
};

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

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

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

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;

这种情况的目的是:

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

我的问题是:

我应该如何更改函数 foo遵循更高的条件?当前执行 foo适用于 true案例并 move 该局部变量,但以防万一 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

最佳答案

如果你可以把B改成

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

那么 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();
    }
}

Demo

输出是

ctor A
ctor A
125
------
1
dtor A
dtor A

关于c++ - 如何延长局部变量的生命周期或使用引用的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233129/

相关文章:

c++ - 匿名对象的属性

c++ - Qt:创建一个滚动条,后面有一个阴影,它包含最后一个值

c++ - 销毁从工厂方法初始化的引用成员

c++ - 如何通过单击按钮将 QMenu 文本从英语更改为俄语

c++ - 如何在非模板类中存储仿函数?

c++ - 函数参数作为引用以避免检查 NULL

c# - c# 创建函数和引用对象

c++ - 带有可变模板参数的 boost::format

c++ - 为什么 bool [][] 比 vector<vector<bool>> 更有效

c++ - 在 std vector 中存储对象的正确方法