小编Nam*_*ame的帖子

为什么字符串的 move() 会改变内存中的底层数据位置?

我试图通过 string_view 将一些字符串保存到第二个数据容器,但遇到了一些困难。事实证明,字符串在 move() 之后改变了它的底层数据存储。

我的问题是,为什么会发生这种情况?

例子:

#include <iostream>
#include <string>
#include <string_view>
using namespace std;

int main() {
    string a_str = "abc";
    cout << "a_str data pointer: " << (void *) a_str.data() << endl;

    string_view a_sv = a_str;

    string b_str = move(a_str);
    cout << "b_str data pointer: " << (void *) b_str.data() << endl;
    cout << "a_sv: " << a_sv << endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:

a_str data pointer: 0x63fdf0
b_str data pointer: 0x63fdc0
a_sv:  bc
Run Code Online (Sandbox Code Playgroud)

感谢您的回复!

c++ move-semantics c++17

2
推荐指数
2
解决办法
72
查看次数

调用或不调用 abs() 函数,取决于模板类型是无符号的,如果可能的话?

试图编译代码:

template<typename K, typename V>
typename ConcurrentMap<K, V>::Access ConcurrentMap<K, V>::operator[](const K &key) {
//    auto ind = abs(static_cast<long long>(key)) % bucket_count;
    auto ind = abs(key) % bucket_count;
    return {lock_guard<mutex>(mutexes[ind]), sub_maps[ind][key]};
}
Run Code Online (Sandbox Code Playgroud)

并得到一个错误:

error: call of overloaded 'abs(const long long unsigned int&)' is ambiguous
Run Code Online (Sandbox Code Playgroud)

错误是因为模板参数 K 是无符号的。因此,不能对其调用 abs() 。

如果模板参数 K 未签名,我可以禁用对 abs() 的调用吗?

或者请针对此类情况提出一些最佳实践解决方案。谢谢!

c++ templates

0
推荐指数
1
解决办法
48
查看次数

标签 统计

c++ ×2

c++17 ×1

move-semantics ×1

templates ×1