【发布时间】:2023-02-02 17:04:30
【问题描述】:
假设有一个全局的Foo对象,
struct Foo {
int i;
~Foo() { std::cout << "gone: " << i << std::endl; }
};
Foo globalFoo{7};
它可以通过一个通过引用返回它的函数来检索,
Foo& getFoo() {
return globalFoo;
}
并且还有一个工厂功能可以凭空制作一个不同的Foo,
std::unique_ptr<Foo> makeFoo() {
return std::make_unique<Foo>(5);
}
以上是不变的。
在客户端代码中,是否应该使用makeFoo或getFoo由运行时bool决定。
int main()
{
bool b{false};
std::cin >> b;
/* type */ foo = b
? /* via getFoo */
: /* via makeFoo */;
}
处理这种情况的适当方法是什么?
我可以说这不是方法:
auto& foo = b
? getFoo()
: *makeFoo();
因为 foo 在创建 as the temporary result of makeFoo(), the unique_ptr will be destoryed 之后是一个悬空引用,因此将托管 Foo 带走。
这也不是办法:
auto& foo = b
? getFoo()
: *makeFoo().release();
because the object *makeFoo().release() is leaked,除非I manually delete it。
【问题讨论】:
-
可以复制对象吗?或者您是否需要使用对原始对象的引用(在全局变量的情况下)?
标签: c++ memory-management c++17 smart-pointers unique-ptr