使用将unique_ptr移动到相同对象构造的基类之后,使用指向对象的原始指针初始化字段

如何解决使用将unique_ptr移动到相同对象构造的基类之后,使用指向对象的原始指针初始化字段

我有一个Foo拥有的对象Owner,没有其他人。我创建了一个类Derived的对象,该对象继承了Owner,并将其unique_ptr传递给了新创建的FooDerived有一个类User的成员,该成员也需要使用Foo,但它并不拥有它,因此它仅获得指向它的原始指针。

#include <memory>
#include <iostream>
using namespace std;

struct Foo {
  void talk() { cout << "foo" << endl; }
};

struct User {
  Foo *foo;
  User(Foo *_foo): foo(_foo) {};
  void use() { foo->talk(); } //potential disaster if foo's memory has changed
};

struct Owner {
  unique_ptr<Foo> foo;
  Owner(unique_ptr<Foo> _foo): foo(move(_foo)) {};
};

struct Derived : public Owner {
  User user;
  Derived(unique_ptr<Foo> _foo)
  : Owner {move(_foo)},user{_foo.get()}  //potential disaster: _foo has already been move()'d,can't get()!
  {};
  void use() { user.use(); };
};

int main() {
  Derived d(make_unique<Foo>());
  //do other stuff
  d.use();  //potential disaster
}

问题在于,在Derived的初始化列表中,我需要move() Foo并将其传递给Owner的构造函数(采用{{ 1}},因为它是所有者),并且还向unique_ptr<Foo>传递了指向Foo的原始指针。但是到User初始化时,User已经被移动,unique_ptr<Foo>可能指向无效的位置!

什么是确保foo.get()获得指向User的有效(非所有权)指针并且Foo仍然获得其Owner的好方法?

解决方法

您可以使基类的成员受到保护(或具有更高的可访问性),并引用基类

Derived(unique_ptr<Foo> _foo)
  : Owner {move(_foo)},user{foo.get()} // refers to Owner::foo
,

您可以在复制指针的同时将工作委托给私有构造函数:

struct Derived : public Owner {
  User user;
  Derived(unique_ptr<Foo> _foo)
  : Derived(move(_foo),_foo.get())
  {};

  void use() { user.use(); };
private:
  // Implement the real logic here
  // As pointed by @Artyer in the comments,this r-value ref is required. 
  // Pass by value would again introduce UB in the calling code.
  Derived(unique_ptr<Foo>&& _foo,Foo* ptr)
   : Owner {move(_foo)},user{ptr} {}
};

请注意,Derived(move(_foo),_foo.get())是安全的,即使未指定评估顺序,因为std::move只是强制转换。

为清楚起见,这不是潜在的灾难,而是一定的灾难 因为初始化列表是从左到右评估的。

9.4.4.4 [dcl.init.list]

在 大括号初始列表的初始列表,初始子句, 包括任何因包装膨胀([temp.variadic])而产生的结果, 按照它们出现的顺序进行评估。 也就是说,每个值 与给定的初始化子句相关的计算和副作用 在每次值计算和相关副作用之前进行排序 与任何以逗号分隔的跟随其后的初始化子句 初始化列表的列表。 [注意:此评估顺序适用 不论初始化的语义如何;例如,它 当初始化列表的元素解释为 构造函数调用的参数,即使通常没有 对调用参数的排序约束。 —尾注]

已添加:为什么私有构造函数需要通过引用传递

@Artyer发布了带有反例的正确说明,但很遗憾,此后已将其删除。

有两种合理的方式来编写委托的构造函数:

Derived(unique_ptr<Foo>&& _foo,Foo* ptr) //(A)
Derived(unique_ptr<Foo> _foo,Foo* ptr) //(B) Since the move is cheap.

并假设它是这样命名的:

Derived(move(_foo),_foo.get()) //(1)
Derived{move(_foo),_foo.get()} //(2) @Artyer's idea

首先,通过添加委派的构造函数,我们实质上添加了一个顺序点,该顺序点必须先评估唯一指针和原始指针,然后再将它们分别传递到OwnerUser

第二,必须在实际调用函数之前对函数调用的所有参数进行求值,()的顺序未指定,{}的顺序从左至右(请参见上面的删除段落) )。

区别在于,如果使用(B),则必须在呼叫处进行复制,对于(),可以在将_foo.get()分配给ptr之前复制该副本。论据。对于{},它总是会在之前发生。因此错误地设置了ptr

另一方面,如果选择(A),则仅将r值引用复制到参数中,并且无论ptr或{{1 }}。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-