我刚刚尝试使用启用了-std=c++11选项的g++ 4.7(较新的快照之一)进行实验。我尝试编译我的一些现有代码库,但其中一个失败的案例让我有些困惑。
如果有人能够解释一下发生了什么,我将不胜感激。
这是代码:
#include <utility>
#include <iostream>
#include <vector>
#include <string>
int main ( )
{
std::string s = "abc";
// 1 ok
std::pair < std::string, int > a = std::make_pair ( s, 7 );
// 2 error on the next line
std::pair < std::string, int > b = std::make_pair < std::string, int > ( s, 7 );
// 3 ok
std::pair < std::string, int > d = std::pair < std::string, int > ( s, 7 );
return 0;
}
我理解make_pair应该用作(1)情况,如果我指定了类型,那我也可以使用(3),但我不明白为什么在这种情况下它会失败。
具体错误如下:
test.cpp: In function ‘int main()’:
test.cpp:11:83: error: no matching function for call to ‘make_pair(std::string&, int)’
test.cpp:11:83: note: candidate is:
In file included from /gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/utility:72:0,
from test.cpp:1:
/gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/bits/stl_pair.h:274:5:
note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_T1>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
/gcc4.7/usr/local/lib/gcc/i686-pc-linux-gnu/4.7.0/../../../../include/c++/4.7.0/bits/stl_pair.h:274:5:
note: template argument deduction/substitution failed:
test.cpp:11:83: note: cannot convert ‘s’ (type ‘std::string {aka std::basic_string<char>}’) to type ‘std::basic_string<char>&&’
这里的问题仅限于“发生了什么?”我知道可以通过删除模板规范来解决问题,但我只想知道在幕后失败的原因。
- g++ 4.4编译此代码没有任何问题。
- 删除-std=c++11也可以编译此代码并且没有任何问题。
std::vector
构造函数中的破坏性变更。至少这个变更会产生编译器错误,而不是在语义上默默地改变。 - James McNellis