我正在开发一些类(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();
}
}
输出是
ctor A
ctor A
125
------
1
dtor A
dtor A
关于c++ - 如何延长局部变量的生命周期或使用引用的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45233129/