问题描述
#include< iostream>#include< vector>使用命名空间std;int main(void){向量< int>一种;a.push_back(3);向量< int>b = move(a);cout <b:<b.data()<endl;cout <a:<a.data()<endl;返回0;}
输出(在c ++ 98中):
b:0x7f9a82405730a:0x7f9a82405720
输出(在c ++ 11中):
b:0x7f9a82405730a:0x0
我正在使用Apple clang 11.0.3.
第一个输出不使用编译器标志.
-std = c ++ 11
标志用于第二个输出.
我知道move()在c ++ 11(及更高版本)中的作用.但是正如我所看到的,在c ++ 98中使用move()对传递的对象没有任何作用,只会进行深度复制.
然后为什么在c ++ 98中有一个move()?
在C ++ 11之前的所有版本中都可以调用 std :: move
的原因是libc ++不会包装中使用href ="https://github.com/llvm/llvm-project/blob/6d3b81664a4b79b32ed2c2f46b21ab0dca9029cc/libcxx/include/type_traits#L2613-L2622" rel ="noreferrer">其实现 #if _LIBCPP_STD_VER> = 11 .这在libstdc ++(Linux默认使用的)中不起作用,因为它使用 #if __cplusplus> = 201103L
来保护 std :: move
.
至于为什么使用它不会使 a.data()
为null,这是因为libc ++ 确实将move构造函数包装在 #ifndef _LIBCPP_CXX03_LANG
中,因此它退回到了副本构造函数中./p>
#include <iostream>
#include <vector>
using namespace std;
int main(void){
vector<int> a;
a.push_back(3);
vector<int> b = move(a);
cout<<"b: "<<b.data()<<endl;
cout<<"a: "<<a.data()<<endl;
return 0;
}
Output (in c++98):
b: 0x7f9a82405730
a: 0x7f9a82405720
Output (in c++11):
b: 0x7f9a82405730
a: 0x0
I am using Apple clang 11.0.3.
No compiler flags are used for the first output.
-std=c++11
flag for the second output.
I know what move() does in c++11 (and higher versions).But as I can see using move() in c++98 does nothing to the object passed and just deep copy happens.
Then why is there a move() in c++98??
The reason that you can call std::move
at all pre-C++11 is that libc++ doesn't wrap its implementation of it in #if _LIBCPP_STD_VER >= 11
. This doesn't work in libstdc++ (which Linux uses by default) because it guards std::move
with #if __cplusplus >= 201103L
.
As for why using it doesn't make a.data()
be null, it's because libc++ does wrap the move constructor in #ifndef _LIBCPP_CXX03_LANG
, so it falls back to the copy constructor.
这篇关于什么是c ++ 98中的move()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!