And*_*Dog 2 c++ move-semantics c++11
假设我有一个与std :: vector兼容的非STL向量类型operator std::vector<T>.是否可以将其元素移动到std :: vector而不是默认的复制结构,这样就可以了
OtherVectorType<SomeClass> f()
{
OtherVectorType<SomeClass> v;
v.pushBack(SomeClass());
v.pushBack(SomeClass());
v.pushBack(SomeClass());
return v;
}
std::vector<SomeClass> sv = f();
Run Code Online (Sandbox Code Playgroud)
在创建std :: vector时会使用SomeClass的移动构造函数(3次)sv吗?
我想象的东西
template<typename T>
std::vector<T>& operator= (std::vector<T>& self, OtherVectorType<T>&& from)
{
[...]
}
Run Code Online (Sandbox Code Playgroud)
但还没有找到任何有效的解决方案.
为了说明,这是定义std :: vector运算符的方式:
template<typename T> class OtherVectorType
{
[...]
operator std::vector<T>() const
{
if (!m_size)
return std::vector<T>();
return std::vector<T>(reinterpret_cast<T*>(m_pElements),
reinterpret_cast<T*>(m_pElements) + m_size);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你需要支持rvalue引用*this.
operator std::vector<T>() const &; // copy your own type's data
operator std::vector<T>() &&; // move it into the std::vector<T>
Run Code Online (Sandbox Code Playgroud)
可悲的是,支持是罕见的,即使是GCC 4.8也没有.:(
| 归档时间: |
|
| 查看次数: |
384 次 |
| 最近记录: |