c++ - Effective Modern C++ 中的这个项目仍然是最新的吗?
问题描述
有效的现代 C++ 第 146 页:
void processWidget(std::shared_ptr<Widget> spw, int priority);
void cusDel(Widget *ptr);//a custom deleter
这是 C++17 之前的不安全调用:
processWidget(std::shared_ptr<Wdiget>(new Widget, cusDel), computePriority());
它曾经是不安全的,因为可以在构造函数之后new Widget
但之前调用computePriority std::share_ptr
,如果computePriority
产生异常,动态的allcoat Widget 将被泄露。因此你可以这样做:
std::shared_ptr<Widget> spw(new Widget, cusDel);
processWidget(spw, computePriority());
现在这将在 shared_ptr 上添加一个复制构造函数操作。所以你也可以这样做:
std::shared_ptr<Widget> spw(new Widget, cusDel);
processWidget(std::move(spw), computePriority());
所以我的问题是,以下代码是否仍然能够在 C++17 中泄漏内存?
processWidget(std::shared_ptr<Wdiget>(new Widget, cusDel), computePriority());
我已经阅读了这个和这个,但我仍然不确定,我相信std::shared_ptr<Wdiget>(new Widget, cusDel)
并且computePriority()
都在调用 processWidget 之前排序,但是我认为在获得新创建的对象的所有权之后和之前computePriority()
仍然可以抛出异常。new
shared_ptr
解决方案
C++17 did change the sequencing with regard to the evaluation of the expressions used to call a function. While it doesn't impose any particular order, it does say:
The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.
"Indeterminately sequenced" is defined as:
Evaluations A and B are indeterminately sequenced when either A is sequenced before B or B is sequenced before A, but it is unspecified which.
So one parameter will be initialized before the other, including all side-effects. So either the first argument or the second argument is fully evaluated before the other.
推荐阅读
- python - 如何使用 xpath 单击带有 role=button 的标签?
- reactjs - 如果状态为真,如何检查第一次渲染?
- tsql - ROW_NUMBER() 按 [DateCol vs 1] 分区按 DateCol 排序
- ruby - Ruby NoMethodError(未定义的方法 ''...' for '....:Class'
- c# - 如何从另一个访问 UserControl 中的文本框
- r - 将环形 igraph 图的布局更改为一系列水平节点
- java - 如何在 Spring 中非阻塞运行 @PostConstruct?
- variables - SAS代码中的变量有什么问题?
- python - 是否可以更改类型功能的行为?
- azure - 指示 Azure Function App 仅接受 Application/json