c++ - 这个左值返回危险吗?

标签 c++ templates c++14

我有这个代码:

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/

相关文章:

c++ - 如何使用管道发送动态分配的字符串

templates - Odoo <t t-call ="website.layout"> qWebException

c++ - 如何使模板原型(prototype)继承,以便所有特化都继承相同的类/接口(interface)?

c++ - 可变泛型 lambda 和函数重载

c++ - Nemiver 仅显示 ASM 代码

c++ - std::array 中的模板类

c++ - C++17 中结构化绑定(bind)引入的标识符有哪些类型?

c++ - boost program_options自定义解析

c++ - 定义 static constexpr auto 类变量

c++ - 在单个函数中混合 '__try' 和 'try' - 通过 Lambda