免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3409 | 回复: 4
打印 上一主题 下一主题

[C++] std::Move [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-12-09 18:20 |只看该作者 |倒序浏览

[root@localhost mthread]# cat 2.cpp
#include <iostream>
#include <utility>
#include <vector>
#include <string>

int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;

    // uses the push_back(const T&) overload, which means
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";

    // uses the rvalue reference push_back(T&&) overload,
    // which means no strings will copied; instead, the contents
    // of str will be moved into the vector.  This is less
    // expensive, but also means str might now be empty.
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";

    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}
[root@localhost mthread]# gcc --version
gcc (GCC) 4.4.6 20120305 (Red Hat 4.4.6-4)
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

[root@localhost mthread]# g++ -std=c++0x 2.cpp -o 2  
[root@localhost mthread]# ./2
After copy, str is "Hello"
After move, str is "Hello"
The contents of the vector are "Hello", "Hello"

为什么move 之后还是  “hello"?

论坛徽章:
1
巨蟹座
日期:2014-03-18 23:44:30
2 [报告]
发表于 2012-12-09 19:10 |只看该作者
std::move 是C++11的?
我看它的原型是这样的:
Defined in header <algorithm>
               
template< class InputIt, class OutputIt >
OutputIt move( InputIt first, InputIt last, OutputIt d_first );                 (since C++11)

不是有三个参数么,LZ怎么直接给了个 string

论坛徽章:
0
3 [报告]
发表于 2012-12-09 19:20 |只看该作者
g++ 4.7.2 测试无误。

楼主最好看看 g++ 4.4 的 vector 有没有重载 push_back(T&&)。

论坛徽章:
0
4 [报告]
发表于 2012-12-09 20:34 |只看该作者
回复 3# 变异老鼠


    这里和push_back 的关系应该不大, 你的是什么操作系统? 4.7 现在是不是还不稳定?

论坛徽章:
0
5 [报告]
发表于 2012-12-09 23:03 |只看该作者
回复 4# Meets

没有 push_back(T&&) 就只能调用 push_back(T const&),实际做的还是复制而不是移动。

std::move 只是把一个 lvalue 变成 xvalue,并不是说调用了 std::move 就一定发生移动操作。

gcc 4.7 系列都发布大半年了……
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP