移动初始化列表的元素是否安全? [英] Is it safe to move elements of a initializer list?
问题描述
可能重复:
initializer_list和移动语义
在此代码中:
#include <vector>
#include <initializer_list>
template<typename T>
class some_custom_container : public std::vector<T>
{
public:
some_custom_container(const std::initializer_list<T>& contents)
{
for (auto& i : contents)
this->emplace_back(std::move(i));
}
};
class test_class
{};
int main()
{
test_class a;
some_custom_container<test_class> i = { a, test_class(), a };
}
如果我理解, {a,test_class(),a}
是安全构造的:命名对象被复制,未命名的对象被移动来构造initializer_list。之后,此 initializer_list
通过引用 some_custom_container
的构造函数传递。
If I've understand it, all objects in { a, test_class(), a }
are safe-constructed: the named-objects are copied and the unnamed objects are moved to construct the initializer_list. After, this initializer_list
is passed by reference to the some_custom_container
's constructor.
然后,为了避免无用的doble-copy,我移动所有它们填充向量。
Then, to avoid useless doble-copies I move all of them to fill the vector.
这个构造函数是否安全?我的意思是,在一个奇怪的情况下,例如如果T被评估为参考&
Is it safe this constructor? I mean, in a strange situation, for example if T is evaluated as a reference & or &&, is the vector always well-filled (contains it safe objects)?
如果是这种情况,为什么 initializer_list
stl容器的构造函数实现没有以这种方式实现?
If this is the case, why the initializer_list
constructor implementations of stl containers aren't implemented in this way? As I know, their constructors copy and don't move the contents.
推荐答案
initializer_list
只提供 const
访问其元素。你可以使用 const_cast
来编译代码,但是移动可能会导致未定义的行为(如果 initializer_list
是真正的const)。所以,没有不安全做这个移动。有这是的解决方法,如果你真的需要它。
initializer_list
only provides const
access to its elements. You could use const_cast
to make that code compile, but then the moves might end up with undefined behaviour (if the elements of the initializer_list
are truly const). So, no it is not safe to do this moving. There are workarounds for this, if you truly need it.
这篇关于移动初始化列表的元素是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!