初始化列表和移动语义
我可以将元素移出 std::initializer_list
吗?
#include <initializer_list>
#include <utility>
template<typename T>
void foo(std::initializer_list<T> list)
{
for (auto it = list.begin(); it != list.end(); ++it)
{
bar(std::move(*it)); // kosher?
}
}
由于 std::intializer_list
需要特殊的编译器注意,并且不像 C++ 标准库的普通容器那样具有值语义,因此我宁愿安全,也不愿抱歉并询问。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不,这不会按预期工作;您仍然会得到副本。我对此感到非常惊讶,因为我认为
initializer_list
的存在是为了保留临时数组,直到它们被移动
为止。initializer_list
的begin
和end
返回const T *
,因此move
的结果在您的代码中是T const &&
— 一个不可变的右值引用。这样的表达方式无法被有意义地移走。它将绑定到类型T const &
的函数参数,因为右值确实绑定到 const 左值引用,并且您仍然会看到复制语义。原因可能是编译器可以选择将
initializer_list
设为静态初始化常量,但将其类型设为initializer_list
或constinitializer_list
由编译器自行决定,因此用户不知道是否期望begin
得到const
还是可变结果结束
。但这只是我的直觉,也许我错了有充分的理由。更新:我写了 ISO 提案,用于支持仅移动类型的
initializer_list
。这只是初稿,尚未在任何地方实现,但您可以查看它以对问题进行更多分析。No, that won't work as intended; you will still get copies. I'm pretty surprised by this, as I'd thought that
initializer_list
existed to keep an array of temporaries until they weremove
'd.begin
andend
forinitializer_list
returnconst T *
, so the result ofmove
in your code isT const &&
— an immutable rvalue reference. Such an expression can't meaningfully be moved from. It will bind to an function parameter of typeT const &
because rvalues do bind to const lvalue references, and you will still see copy semantics.Probably the reason for this is so the compiler can elect to make the
initializer_list
a statically-initialized constant, but it seems it would be cleaner to make its typeinitializer_list
orconst initializer_list
at the compiler's discretion, so the user doesn't know whether to expect aconst
or mutable result frombegin
andend
. But that's just my gut feeling, probably there's a good reason I'm wrong.Update: I've written an ISO proposal for
initializer_list
support of move-only types. It's only a first draft, and it's not implemented anywhere yet, but you can see it for more analysis of the problem.不是按照你想要的方式。您无法移动
const
对象。并且std::initializer_list
仅提供对其元素的const
访问。所以it
的类型是const T *
。您尝试调用
std::move(*it)
只会产生左值。即:副本。std::initializer_list
引用静态内存。这就是课程的目的。你不能从静态内存中移动,因为移动意味着改变它。您只能从中复制。Not in the way that you intend. You cannot move a
const
object. Andstd::initializer_list
only providesconst
access to its elements. So the type ofit
isconst T *
.Your attempt to call
std::move(*it)
will only result in an l-value. IE: a copy.std::initializer_list
references static memory. That's what the class is for. You cannot move from static memory, because movement implies changing it. You can only copy from it.这不会像所说的那样工作,因为
list.begin()
的类型是const T *
,并且您无法从常量对象移动。语言设计者这样做可能是为了允许初始值设定项列表包含例如字符串常量,从该列表中移动是不合适的。但是,如果您知道初始值设定项列表包含右值表达式(或者您想强制用户编写这些表达式),那么有一个技巧可以使其工作(我受到 Sumant 的回答的启发)这个,但解决方案比那个简单得多)。您需要存储在初始化列表中的元素不是
T
值,而是封装T&&
的值。然后,即使这些值本身是 const 限定的,它们仍然可以检索可修改的右值。现在,您不再声明 智能指针向量,仅定义了移动语义(因此这些对象本身永远不能存储在初始值设定项列表中);但下面的初始化列表编译没有问题。
initializer_list
参数,而是声明initializer_list 参数。 >
参数。这是一个具体的例子,涉及一个 std::unique_ptr有一个问题确实需要答案:如果初始值设定项列表的元素应该是真正的纯右值(在示例中它们是x值),那么该语言是否确保相应临时变量的生命周期延伸到它们被使用的时间点?坦率地说,我认为该标准的相关第 8.5 节根本没有解决这个问题。然而,阅读 1.9:10,似乎所有情况下相关的完整表达式都包含了初始化列表的使用,所以我认为不存在悬空右值引用的危险。
This won't work as stated, because
list.begin()
has typeconst T *
, and there is no way you can move from a constant object. The language designers probably made that so in order to allow initializer lists to contain for instance string constants, from which it would be inappropriate to move.However, if you are in a situation where you know that the initializer list contains rvalue expressions (or you want to force the user to write those) then there is a trick that will make it work (I was inspired by the answer by Sumant for this, but the solution is way simpler than that one). You need the elements stored in the initialiser list to be not
T
values, but values that encapsulateT&&
. Then even if those values themselves areconst
qualified, they can still retrieve a modifiable rvalue.Now instead of declaring an
initializer_list<T>
argument, you declare aninitializer_list<rref_capture<T> >
argument. Here is a concrete example, involving a vector ofstd::unique_ptr<int>
smart pointers, for which only move semantics is defined (so these objects themselves can never be stored in an initializer list); yet the initializer list below compiles without problem.One question does need an answer: if the elements of the initializer list should be true prvalues (in the example they are xvalues), does the language ensure that the lifetime of the corresponding temporaries extends to the point where they are used? Frankly, I don't think the relevant section 8.5 of the standard addresses this issue at all. However, reading 1.9:10, it would seem that the relevant full-expression in all cases encompasses the use of the initializer list, so I think there is no danger of dangling rvalue references.
我认为为解决方法提供合理的起点可能会有所启发。
内嵌评论。
I thought it might be instructive to offer a reasonable starting point for a workaround.
Comments inline.
您可以将参数声明为数组右值引用,而不是使用
std::initializer_list
:请参阅使用
std::unique_ptr
的示例:https://gcc.godbolt.org/z/2uNxv6Instead of using a
std::initializer_list<T>
, you can declare your argument as an array rvalue reference:See example using
std::unique_ptr<int>
: https://gcc.godbolt.org/z/2uNxv6当前标准似乎不允许这样做,因为已经回答了。这是实现类似功能的另一种解决方法,通过将函数定义为可变参数而不是采用初始值设定项列表。
与initializer_list不同,可变参数模板可以适当地处理右值引用。
在此示例代码中,我使用了一组小辅助函数将可变参数转换为向量,以使其与原始代码相似。但是当然,您可以直接使用可变参数模板编写递归函数。
It seems not allowed in the current standard as already answered. Here is another workaround to achieve something similar, by defining the function as variadic instead of taking an initializer list.
Variadic templates can handle r-value references appropriately, unlike initializer_list.
In this example code, I used a set of small helper functions to convert the variadic arguments into a vector, to make it similar to the original code. But of course you can write a recursive function with variadic templates directly instead.
我有一个更简单的实现,它使用一个包装类,该类充当标记来标记移动元素的意图。这是编译时成本。
包装类被设计为以
std::move
的方式使用,只需将std::move
替换为move_wrapper
即可,但是这个需要 C++17。对于较旧的规格,您可以使用额外的构建器方法。您需要编写接受
initializer_list
内的包装类的构建器方法/构造函数,并相应地移动元素。如果您需要复制而不是移动某些元素,请在将其传递给
initializer_list
之前构造一个副本。代码应该是自我记录的。
I have a much simpler implementation that makes use of a wrapper class which acts as a tag to mark the intention of moving the elements. This is a compile-time cost.
The wrapper class is designed to be used in the way
std::move
is used, just replacestd::move
withmove_wrapper
, but this requires C++17. For older specs, you can use an additional builder method.You'll need to write builder methods/constructors that accept wrapper classes inside
initializer_list
and move the elements accordingly.If you need some elements to be copied instead of being moved, construct a copy before passing it to
initializer_list
.The code should be self-documented.
考虑 cpptruths。这个想法是在运行时确定左值/右值,然后调用移动或复制构造。即使initializer_list 提供的标准接口是常量引用,
in
也会检测右值/左值。Consider the
in<T>
idiom described on cpptruths. The idea is to determine lvalue/rvalue at run-time and then call move or copy-construction.in<T>
will detect rvalue/lvalue even though the standard interface provided by initializer_list is const reference.