在 std::tie 中使用 std::weak_ptr::lock()
Using std::weak_ptr::lock() in std::tie
我有一个包含两个弱指针的结构,我希望使用 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
通过引用接收参数,因为它从它们构建了一个引用元组。临时,如lock()
返回的std::shared_ptr
,不能绑定到引用。创建单独的变量为引用提供了要绑定的内容。
std::tie
仅适用于左值,创建返回类型,如std::tuple<T1&, T2&>
。lock()
成员函数按值返回shared_ptr
,因此表达式是右值,不能与std::tie
一起使用。
您可以通过编写std::forward_as_tuple
来更普遍地使用相同的元组词典编纂技巧:
return std::forward_as_tuple(first.lock(), second.lock()) <
std::forward_as_tuple(rhs.first.lock(), rhs.second.lock());
这些forward_as_tuple
调用的返回类型将为std::tuple<std::shared_ptr<int>&&, std::shared_ptr<int>&&>
。forward_as_tuple
通常比tie
更危险,因为它在某些用途中可以创建没有编译器警告的悬空引用,但在这里它是安全的,因为tuple
对象是临时的,在operator<
评估后不会使用。
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- 引用 std::shared:ptr 以避免引用计数
- C++14 unique_ptr并使用已删除的函数'std::unique-ptr' unique_ptr错误
- 使用std :: String ptr的错误打印std :: String
- C++中的大小释放:全局运算符delete的正确行为是什么(void*ptr,std::size_t size)
- std::哈希表示无序映射中的唯一 PTR
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- 正确使用std智能指针以确保ptr安全
- 如何创建 std::string 包装器,它将 ptr 保留为 std::string 和 ptr 到创建该包装器实例的
- 为什么 std::string{ "const char ptr" } 有效?
- 为什么 gcc 4.9.0 中没有定义"void operator delete(void* ptr, std::size_t size) noexcept;"?
- 在 std::map 的值中使用非 ptr 是一种很好的做法吗
- 共享 PTR - C++:std::shared_ptr<T> 和 std::shared_ptr<T const> 有什么区别?