我有这个代码:
struct Base {};
struct Derived : public Base {
int somedata;
};
std::unique_ptr<Base> createTemporary() {
return std::make_unique<Derived>(); // This code has been simplified
}
template<typename T>
T& convertValueTo(std::unique_ptr<Base>&& obj) {
return static_cast<T&>(*obj);
}
int main() {
int data = convertValueTo<Derived>(createTemporary()).somedata;
return 0;
}
我设计了 convertValueTo
模板函数来返回对象的请求类型,主要用于像这样的函数调用
auto some_value = convertValueTo<Something_Else>(createTemporary()).a_member_variable;
现在我想知道.. 有没有更安全的方法来做到这一点?如果有人要使用从 convertValueTo
返回的引用,临时表达式将在行表达式结束时立即销毁,对吗?
我的目标是:
- 允许使用临时对象,如果未存储引用(如上所述),请尽快销毁它
- 允许安全引用绑定(bind)到有效对象,以防有人想要
最佳答案
转换为所需类型的 unique_ptr
。那么谁拥有动态创建的对象的所有权就很清楚了,即从转换函数返回的unique_ptr
。一旦创建了对动态创建对象的左值引用,该引用就有可能在对象的生命周期内继续存在。
#include <memory>
struct Base {};
struct Derived : public Base {
int somedata;
};
std::unique_ptr<Base> createTemporary() {
return std::make_unique<Derived>(); // This code has been simplified
}
template<typename T>
std::unique_ptr<T> convertValueTo(std::unique_ptr<Base>&& obj) {
auto ptr = obj.release ();
return std::unique_ptr<T> { static_cast<T*>(ptr) };
}
int main() {
int data = convertValueTo<Derived>(createTemporary())->somedata;
return 0;
}
关于c++ - 这个左值返回危险吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34363724/