【发布时间】:2012-07-17 12:27:11
【问题描述】:
我有一些代码:
Class A{
//...A has a move ctor here.
};
unordered_map<int, A> bla;
A tmp;
//operations on tmp
bla.insert(make_pair<int, A>(1, move(tmp)));
我想调用移动构造函数而不是 A 类的复制 ctor。这段代码正确吗? 我想是这样。奇怪的是它可以编译并适用于 Ubuntu Precise(g++ 显示版本 4.6.3)。但在 CentOS 上,它无法编译。前几行是:
In substitution of ‘template<class _From1, class _To1> static decltype ((__test_aux<_To1>(declval<_From1>()), std::__sfinae_types::__one())) std::__is_convertible_helper<_From, _To, false>::__test(int) [with _From1 = _From1; _To1 = _To1; _From = const A&; _To = A] [with _From1 = const A&; _To1 = A]’:
/gcc/x86_64-redhat-linux/4.7.1/../../../../include/c++/4.7.1/type_traits:1258:70: required from ‘constexpr const bool std::__is_convertible_helper<const A&, A, false>::value’
/gcc/x86_64-redhat-linux/4.7.1/../../../../include/c++/4.7.1/type_traits:1263:12: required from ‘struct std::is_convertible<const A&, A>’
/gcc/x86_64-redhat-linux/4.7.1/../../../../include/c++/4.7.1/type_traits:116:12: required from ‘struct std::__and_<std::is_convertible<const int&, int>, std::is_convertible<const A&, A> >’
/gcc/x86_64-redhat-linux/4.7.1/../../../../include/c++/4.7.1/bits/stl_pair.h:113:38: required from ‘constexpr std::pair<typename std::__decay_and_strip<_T1>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&) [with _T1 = int; _T2 = A; typename std::__decay_and_strip<_T2>::__type = A; typename std::__decay_and_strip<_T1>::__type = int]’
它似乎试图调用复制ctor。关于这个错误的任何想法?
好吧,我的 CentOS 没有最新版本的 gcc/libstdc++,所以实际上我自己构建了这些(gcc 4.7.1)并将它们安装在我的主目录中。这有关系吗?这是我编译时的配置:
Target: x86_64-redhat-linux
Configured with: ../gcc-4.7.1/configure --prefix=/home/bla/usr/ --with-mpc=/home/bla/usr/ --with-mpfr=/home/bla/usr/ --with-gmp=/home/bla/usr/ --disable-multilib --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++ --enable-java-awt=gtk --disable-dssi --disable-plugin --with-cpu=generic --build=x86_64-redhat-linux
Thread model: posix
gcc version 4.7.1 (GCC)
更新: 也许“移动语义”的使用有问题。我尝试使用 STL 字符串“移动”:
unordered_map<int, string> bla;
string tmp("hello world");
//operations on tmp
bla.emplace(1, move(tmp));
没关系,内部字符真的被“移动”了。
但它不适用于我的 A 类...这是 A:
class A
{
public:
A(){...}
~A(){}
A(A&& other){...}
private:
A& operator = (const A& other);
A& operator = ( A&& other);
A(const A& other);
};
更新: 我搞定了,当 A 是:
class A
{
public:
A(){...}
~A(){}
A(A&& other){...}
A(const A& other){}
private:
A& operator = (const A& other);
A& operator = ( A&& other);
};
注意COPY CTOR。现在我所有的移动语义都正确,并且在运行时 copy ctor 实际上并没有被调用。我对“移动”有什么误解吗?
【问题讨论】:
-
在 Arch Linux 上使用 g++ 4.7.1 测试并且运行良好。
-
如果 libstdc++ 版本足够新,实际上你应该使用
.emplace。bla.emplace(1, std::move(tmp)). -
@AlexFarber 好吧,我想是的。似乎 gcc 无法识别“移动语义”。 gcc -v 显示正确的版本,我会继续跟踪它。
-
@KennyTM 谢谢。我稍后会尝试。据我记得,emplace 直到最近才实施?
-
可变参数模板和右值引用随 GCC 4.3 一起提供。所以
emplace应该出现在 GCC 4.6.3 中。
标签: c++ linux gcc c++11 unordered-map