C++ 当给定这些值类别时,std::pair调用哪个构造函数?
我在查看时注意到,当我通过下面的示例时,C++ 当给定这些值类别时,std::pair调用哪个构造函数?,c++,c++11,C++,C++11,我在查看时注意到,当我通过下面的示例时,std::unique_ptr上的移动有效,但是std::string没有移动 std::string my_str = std::string("Hello World!"); auto my_smartp = std::make_unique<const std::string>(); const std::string &my_str_ref = my_str; // my_str_ref is fine, no move /
std::unique_ptr
上的移动有效,但是std::string
没有移动
std::string my_str = std::string("Hello World!");
auto my_smartp = std::make_unique<const std::string>();
const std::string &my_str_ref = my_str;
// my_str_ref is fine, no move
// my_smartp is fine, no move
auto pair = std::pair<std::string, std::unique_ptr<const std::string>>(my_str_ref, std::move(my_smartp));
// my_str_ref is fine and was not moved
// my_smartp is has been moved to the std::pair
std::string my_str=std::string(“你好,世界!”);
auto my_smartp=std::make_unique();
const std::string&my\u str\u ref=my\u str;
//我的裁判很好,不许动
//我的智能手机很好,不许动
自动对=std::pair(my_str_ref,std::move(my_smartp));
//我的家谱很好,没有移动
//我的_smartp已移动到std::pair
这对我来说毫无意义,因为我能看到的唯一有效的构造函数是(2)
,它传入了两个常量引用,据我所知,这两个常量引用不应该触发任何移动。要么它们都作为临时U1&
和U2&
传递,要么它们都作为常量引用const T1&
和const T2&
传递
如果实现有任何不同,我将使用最新的clang。您正在调用第3个构造函数
template< class U1, class U2 >
pair( U1&& x, U2&& y );
模板
配对(U1和x、U2和y);
U&&是转发引用,可以同时绑定到左值和右值
my_str_ref
是左值
std::move(my_smartp)
是右值
U1被推导为std::string&。
x是一个左值引用:std::string&-因此这里调用了复制构造get
U2被推断为std::unique_ptr.
y是一个右值ref:std::unqiue_ptr&
所以pair.first从我的\u str\u ref中构造副本,pair.second从我的\u smarp中构造移动注意(3)需要的不仅仅是临时变量。这些是普遍的参考;它们可以接受左值和右值引用(彼此独立)重复?