在以下代码中,对logAndProcess的第一个调用选择具有const引用的过程函数,第二个调用选择具有r值引用的过程函数。 我的问题:R值函数不应该移动参数字符串吗?显然不是。为什么?
代码:
#include <string>
#include <stdio.h>
void process(std::string && rvalue)
{
std::string local = rvalue; // shouldn't rvalue have moved to local?
printf("process &&rvalue. local: %s\n",local.c_str());
}
void process(const std::string & rvalue)
{
printf("process const &rvalue\n");
}
template<class T>
void logAndProcess(T &&arg)
{
printf("\nbefore process\n");
process( std::forward<T>(arg) ); // picks the right overload of process one, depending on argument type.
printf("after process\n");
}
main()
{
//logAndProcess(std::string("aaa")); // called with rvalue - calls process(string &&)
std::string tmp("tmp");
logAndProcess(tmp); // calls process(const string &)
printf("tmp not moved: %s\n", tmp.c_str());
logAndProcess(std::move(tmp)); // calls process(string &&)
printf("tmp moved?: %s\n not!", tmp.c_str());
return 0;
}
输出:
before process
process const &rvalue
after process
tmp not moved: tmp
before process
process &&rvalue. local: tmp
after process
tmp moved?: tmp
我理解以下规则:“如果有名称,则为n左值”;但是,在以下示例中,具有左值的变量被移动。具有转发功能的情况有什么不同?
#include <string>
#include <stdio.h>
main()
{
std::string src("aaa");
std::string movedStr = std::move (src);
printf("movedStr: %s src: %s\n", movedStr.c_str(), src.c_str());
return 0;
}
输出:
movedStr: aaa src: