保存我从另一个 class 获得的列表的 const 引用不起作用
Saving a const reference of a list that I get from another class is not working
我的代码有点复杂,不过我觉得结构可以归结为这样,想象一下下面两个class:
class Foo {
std::list<std::shared_ptr<SomeType>> listOfType;
const std::list<std::shared_ptr<SomeType>>& getList() const {
return listOfType;
}
}
class A {
std::shared_ptr<Foo> foo;
Foo getFoo() {
return (*foo);
}
}
现在考虑这三个选项,在 A class 填满 Foo 的列表后:
A a;
// Do something with a, fills the list inside the foo shared pointer
// Option 1, save the copy of foo, then get the const reference of the list
Foo f = a.getFoo();
const std::list<std::shared_ptr<SomeType>>& fList = f.getList();
// Option 2, get a copy of the list directly from the returned copy of foo
std::list<std::shared_ptr<SomeType>> fList = a.getFoo().getList();
// Option 3, get the const list reference directly from the returned copy of foo
const std::list<std::shared_ptr<SomeType>>& fList = a.getFoo().getList();
选项 3 return 是一个空列表,其他两个选项 return 包含预期内容的列表。
我创建这个问题的原因是想知道这段代码是否存在我没有看到的问题(考虑所有引用和共享指针等),否则将是代码问题, 这超出了问题的范围。
谢谢
Foo getFoo() {
return *foo;
}
在此成员函数中,您正在 returning 一个临时变量,它是调用表达式中的纯右值。因为你在上面调用 .getList() ,它会具体化并成为一个 xvalue(过期值),一旦表达式完成,它就会被销毁,因为你正在捕获 returned 列表的引用来自第三个 'option' 中的临时对象,它将成为悬空引用。
Foo & getFoo() {
return *foo;
}
但是,如果您 return 引用,它将在调用表达式中被视为左值,因此列表不会成为悬空引用。
我的代码有点复杂,不过我觉得结构可以归结为这样,想象一下下面两个class:
class Foo {
std::list<std::shared_ptr<SomeType>> listOfType;
const std::list<std::shared_ptr<SomeType>>& getList() const {
return listOfType;
}
}
class A {
std::shared_ptr<Foo> foo;
Foo getFoo() {
return (*foo);
}
}
现在考虑这三个选项,在 A class 填满 Foo 的列表后:
A a;
// Do something with a, fills the list inside the foo shared pointer
// Option 1, save the copy of foo, then get the const reference of the list
Foo f = a.getFoo();
const std::list<std::shared_ptr<SomeType>>& fList = f.getList();
// Option 2, get a copy of the list directly from the returned copy of foo
std::list<std::shared_ptr<SomeType>> fList = a.getFoo().getList();
// Option 3, get the const list reference directly from the returned copy of foo
const std::list<std::shared_ptr<SomeType>>& fList = a.getFoo().getList();
选项 3 return 是一个空列表,其他两个选项 return 包含预期内容的列表。
我创建这个问题的原因是想知道这段代码是否存在我没有看到的问题(考虑所有引用和共享指针等),否则将是代码问题, 这超出了问题的范围。
谢谢
Foo getFoo() {
return *foo;
}
在此成员函数中,您正在 returning 一个临时变量,它是调用表达式中的纯右值。因为你在上面调用 .getList() ,它会具体化并成为一个 xvalue(过期值),一旦表达式完成,它就会被销毁,因为你正在捕获 returned 列表的引用来自第三个 'option' 中的临时对象,它将成为悬空引用。
Foo & getFoo() {
return *foo;
}
但是,如果您 return 引用,它将在调用表达式中被视为左值,因此列表不会成为悬空引用。