如何初始化含引用成员的std::pair?C++编译错误求助
问题分析与解决方案
错误原因
编译错误的核心是std::make_pair的类型推导规则:当传入左值(比如static变量s_s1)时,它会默认推导为值类型而非引用类型。因此std::make_pair(std::string("abc"), s_s1)返回的是std::pair<std::string, std::string>,但函数声明的返回值是std::pair<std::string, std::string&>,这两个类型无法隐式转换,导致编译失败。
修复方案
以下三种方法都可以解决这个问题:
方案1:直接构造std::pair并显式指定模板参数
直接创建目标类型的std::pair,跳过make_pair的自动推导:
#include <vector> #include <string> #include <utility> std::pair<std::string, std::string&> foo() { static std::string s_s1{ "the~static" }; return std::pair<std::string, std::string&>(std::string("abc"), s_s1); // 直接构造目标类型 } int main() { extern std::pair<std::string, std::string&> foo(); std::vector<std::string> coll; coll.push_back(foo().first); coll.push_back(foo().second); return 0; }
方案2:用std::ref包装引用成员的参数
std::ref会返回一个std::reference_wrapper,让make_pair推导时识别出引用类型:
#include <vector> #include <string> #include <utility> #include <functional> // 需包含此头文件使用std::ref std::pair<std::string, std::string&> foo() { static std::string s_s1{ "the~static" }; return std::make_pair(std::string("abc"), std::ref(s_s1)); // 用std::ref包装引用参数 } int main() { extern std::pair<std::string, std::string&> foo(); std::vector<std::string> coll; coll.push_back(foo().first); coll.push_back(foo().second); return 0; }
方案3:显式指定std::make_pair的模板参数
强制make_pair生成目标类型的pair:
#include <vector> #include <string> #include <utility> std::pair<std::string, std::string&> foo() { static std::string s_s1{ "the~static" }; return std::make_pair<std::string, std::string&>(std::string("abc"), s_s1); // 显式指定模板参数 } int main() { extern std::pair<std::string, std::string&> foo(); std::vector<std::string> coll; coll.push_back(foo().first); coll.push_back(foo().second); return 0; }
验证说明
三种方案都能让代码正常编译,并且保留原逻辑:
foo().first是xvalue,会触发push_back的移动构造,避免拷贝foo().second是左值引用,会触发push_back的拷贝构造,符合原代码注释的预期
内容的提问来源于stack exchange,提问作者Jimm Chen
相关产品推荐
相关产品推荐

