std::string and move_iterator
std::string and move_iterator
我正在编写一个标记化器,它将拆分一个string
并将每个字段放入一个vector
中。我的想法是反复使用string::find
。我没有使用临时的string
对象,而是使用了move_iterator
s,因为我认为在算法处理原始字符串时,它的字符会被窃取。但这并没有发生。
这是一个示例代码,演示了我所说的内容:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
void
print_strings
( const vector<string> & v )
{
unsigned int i = 1;
for ( const auto & s : v )
cout << "#" << i++ << "t: "" << s << """ << endl;
return;
}
int
main
( void )
{
string base( "hello, this is an example string, I like icescreams" );
/* Vector to populate with strings */
vector<string> v;
/* 1: a copy of 'base' */
v.emplace_back( base );
/* 2: a copy of 'base' using iterators */
v.emplace_back( base.begin() , base.end() );
/* 3: a string that I think _should_ move from 'base' */
v.emplace_back( make_move_iterator(base.begin()) , make_move_iterator(base.end()) );
/* Print the strings twice so that we
* can see if something has changed. */
print_strings( v );
print_strings( v );
return 0;
}
使用g++ -std=c++11 -Wall -Wextra -Werror -O2
编译时,它不会显示任何警告。
我的猜测是,string
的构造函数,在其范围版本中,总是从指定范围复制。由于我不确定,我想确定,当然,看看你用过什么变通办法。
谨致问候,Kalrish
Iterator对容器一无所知。
move_iterator
不能神奇地从字符串中移动。它不能只从其底层元素(即单个char
)中移动,从char中移动与复制它相同。您需要使用std::move(base)
。
#include <vector>
#include <string>
#include <iostream>
using namespace std;
void
print_strings
( const vector<string> & v )
{
unsigned int i = 1;
for ( const auto & s : v )
cout << "#" << i++ << "t: "" << s << """ << endl;
return;
}
int
main
( void )
{
string base( "hello, this is an example string, I like icescreams" );
/* Vector to populate with strings */
vector<string> v;
/* 1: a copy of 'base' */
v.emplace_back( base );
/* 2: a copy of 'base' using iterators */
v.emplace_back( base.begin() , base.end() );
/* 3: a string that I think _should_ move from 'base' */
std::cout << base << 'n'; // base is still untouched here
v.emplace_back( std::move(base) ); // now it'll be moved from
print_strings( v );
std::cout << "base: " << base << "/basen"; // base is empty
return 0;
}
在这里直播吧。
相关文章:
- 瓦尔格林德:数学函数"Conditional jump or move depends on uninitialised value(s)"
- Usages of std::move
- 在C++中对T*类型执行std::move的意外行为
- 关于std::move的使用,是否有编译警告
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 通过实例理解std::move及其目的
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 是否可以在 C++03 中定义'move-and-swap idiom'等效项
- 返回一个带有 std::move 的对象并链接函数
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 为什么字符串的 move() 会改变内存中底层数据的位置?
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 在调试模式下引发C++ "deque iterator not dereferencable"异常
- std::iterator::reference 必须是引用吗?
- 为什么当我为 for(auto& it : myUnorderedMap) {... = std::move(it.second)} 时,我会得到一个 const 引用?
- 添加自定义析构函数时,Move 构造函数在派生类中消失
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- CPP 中的瓦尔格林德和记忆泄漏:"Conditional jump or move depends on uninitialised values"
- std::move a const std::vector in a lambda capture
- Clang Modules 与 std <iterator> 和 <boost/move/iterator.hpp 的交互>