副作用/易失性/复制构造函数/析构函数
参考此处的讨论
$3.7.1/ 2 - “如果静态存储持续时间的对象具有初始化或具有副作用的析构函数,则即使它看起来未使用,也不得将其消除,但类对象或其副本可以按照 12.8 中的规定消除。”
$12.8/15-“当满足某些条件时,允许实现省略类对象的复制构造,即使该对象的复制构造函数和/或析构函数有副作用。”
是上述情况,是一种情况的具体示例,其中甚至易失性读/写也可以被优化掉(例如,如果复制构造函数具有对易失性变量的读/写)。
所以问题是“即使复制构造函数具有 volatile 变量的读/写功能,也可以省略复制构造函数吗?”
With reference to the discussion here
$3.7.1/2 - "If an object of static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy may be eliminated as specified in 12.8."
$12.8/15- "When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects."
Is the above case, specific examples of a case, where even a volatile read/write may also be optimized away (e.g. if a copy constructor has a read/write to a volatile variable).
So the question is "can a copy constructor be elided even if the copy constructor has a read/write of a volatile variable?"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当命名对象是非易失性的时才允许使用 NRVO [它就在您引用的同一部分中,第一个项目符号],但除此之外我不明白为什么不可以。毕竟,如果您创建的对象是易失性的,您仍然在写入它,只是没有通过复制构造函数这样做。而且它没有限定允许忽略哪些副作用,因此很明显,如果易失性读/写位于复制构造函数本身内,则编译器不必关心。
NRVO is only allowed if the named object is non-volatile [its right in the same section you quoted, the first bullet], but otherwise I don't see why not. After all, if the object you are creating is volatile, you are still writing to it, you just aren't doing so via the copy constructor. And it doesn't qualify which side effects it is allowed to ignore, so clearly if the volatile read/write is within the copy constructor itself the compiler doesn't have to care.
有时。有趣的是,你应该问这个问题,因为我错误地记住了一些关于
易失性
的事情(约翰内斯喊出了这一点),这导致我去查找这样的琐事。§12.8/15:
因此,可以通过省略构造函数来消除
易失性
访问,但如果整个对象是易失性的,则不行。此外,如果一个函数按值返回
易失性foo
,而不是简单的foo
,它可能会有所不同,因为不稳定临时的构建不能被忽略!请注意,返回的临时对象的 cv 限定也会影响临时对象的访问语义,例如
factory_b().non_const_method()
是非法的。所以这比愚蠢更神秘。Sometimes. Funny you should ask, since something I mis-remembered about
volatile
(which Johannes called out) led me to look up exactly such trivia.§12.8/15:
So, it's OK to eliminate a
volatile
access by eliding the constructor, but not if the entire object is volatile.Also, it can make a difference if a function returns
volatile foo
by value as opposed to plainfoo
, because construction of the volatile temporary cannot be elided!Note that the cv-qualification of the returned temporary also affects access semantics of the temporary, for example
factory_b().non_const_method()
is illegal. So this is all more arcane than boneheaded.