c++ - 在 std::tie 中使用 std::weak_ptr::lock()
问题描述
我有一个包含两个弱指针的结构,我希望使用 std::tie 按字典顺序比较这个结构。但是,我遇到了一个奇怪的问题,我意识到我不能使用 std::weak_ptr::lock() 作为 std::tie 的参数。示例代码:
struct S {
S(std::shared_ptr<int>& f, std::shared_ptr<int>& s) {
first = f;
second = s;
}
bool operator<(const S& rhs) const {
return std::tie(first.lock(), second.lock()) < std::tie(rhs.first.lock(), rhs.second.lock());
}
std::weak_ptr<int> first, second;
};
这样做会导致编译错误,代码为E0304
: no instance of function template "std::tie" matches the argument list
。
但是,如果我创建新std::shared_ptr
对象并将它们设置为 std::weak_ptr::lock() 的值,然后比较它们,一切正常:
struct S {
S(std::shared_ptr<int>& f, std::shared_ptr<int>& s) {
first = f;
second = s;
}
bool operator<(const S& rhs) const {
// creating shared_ptrs and assigning them the value of std::weak_ptr::lock()
std::shared_ptr<int>
f = first.lock(), s = second.lock(),
rf = rhs.first.lock(), rs = rhs.second.lock();
// compare those shared_ptrs
return std::tie(f, s) < std::tie(rf, rs);
}
std::weak_ptr<int> first, second;
};
int main() {
std::shared_ptr<int>
a(new int(10)),
b(new int(5));
// just two S initializations
S foo(a, b);
S bar(b, a);
if (foo < bar) {
std::cout << "Foo is less than Bar";
}
else {
std::cout << "Otherwise";
}
}
输出:Foo is less than Bar
这可能是什么原因?谢谢!
解决方案
std::tie
通过引用接收参数,因为它从它们构建一个引用元组。临时对象,如std::shared_ptr
返回的lock()
,不能绑定到引用。创建单独的变量会给引用绑定一些东西。
推荐阅读
- java - H2 参照完整性约束违反
- java - 如何在浏览器中打开 JSP 页面的 UI?
- .net-core - .NetCore 2.2:如何获取证书的私钥?
- odoo - AttributeError:类型对象'######'没有属性'#########'
- oracle - 导入oracle多个dump文件
- jquery - Show/Hide overlapping content below the previous inside Table
- php - 如何在 Woocommerce 中访问受保护的数据?
- php - 是否可以在 Symfony 4 中获取 DBALException 的参数?
- php - 如何在drupal 7视图中使引用的列可排序
- python - SKlearn GBM 特征重要性或“预测”方法的贡献者