Placement-new 是否引入了序列点?
考虑以下代码行:
new (p++) T();
如果构造函数 T()
抛出异常,是否保证 p
已经递增?
Consider the following line of code:
new (p++) T();
If the constructor T()
throws an exception, is p
guaranteed to have already been incremented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从 5.3.4 [expr.new] (引用自 n3242):
因此,在新表达式中,分配函数是从函数调用中使用的(这是有道理的)。所有分配函数都是函数,包括实现提供的函数,来自 3.7.4.1 [basic.stc.dynamic.allocation]:
因此,当构造函数抛出异常时,分配已经发生,并且关联的函数调用表达式已被完全求值。
From 5.3.4 [expr.new] (quoting from n3242):
So in a new expression the allocation function is used from a function call (which makes sense). All allocation functions are functions, including the ones provided by the implementation, from 3.7.4.1 [basic.stc.dynamic.allocation]:
So by the time an exception is thrown from the constructor, the allocation has taken place and the associated function call expression has been fully evaluated.
是的,它保证会增加。
运算符只是函数/方法调用的语法糖。
我不认为 new 在运算符之上有任何特殊含义,因此它应该是相同的。
因此,在调用函数
new
之前,所有参数都会被完全评估(带有序列点)。Yes it is guaranteed to be incremented.
The operators are just syntactic sugar for function/method calls.
I don't believe new has any special meaning above operator so it should be the same.
Thus all parameter are fully evaluated (with sequence point) before the function
new
is called.我认为该标准没有直接/明确回答这个问题。然而,隐含的答案是肯定的。
特别是,new 的放置语法只是一种指定将传递给函数的额外参数的方法。与任何其他函数调用一样,在计算函数的所有参数(按未指定的顺序)和执行函数中的任何代码之间存在一个序列点。我相信这应该意味着您的
p++
将在其他任何事情发生之前进行评估并应用所有副作用。I don't think the standard answers this question directly/explicitly. Implicitly, however, the answer is yes.
In particular, the placement syntax for new is simply a way of specifying extra parameters that will be passed to a function. Like any other function call, there is a sequence point between evaluating all the parameters to the function (in unspecified order), and executing any code in the function. I believe that should mean your
p++
will be evaluated and all side effects applied before anything else happens.Placement new 只是一个常规函数,名为
operator new(size_t, void*)
。它只是返回第二个参数。Placement new is just a regular function, named
operator new(size_t, void*)
. It simply returns its second argument.增量运算符执行以下操作:
因此,
p
保证会递增。The increment operator does the following:
So,
p
is guaranteed to be incremented.