小编pat*_*oft的帖子

C++ copy elision用于引用

考虑到以下简化代码,Cache :: operator []的调用者保证接收映射值的副本?

#include <string>
#include <map>
#include <mutex>
#include <iostream>

class Cache {
    public:
        std::string operator[] (int k) {
            std::lock_guard<std::mutex> lock(m_mutex);

            if (! m_map.count(k)) m_map[k] = "Hello world";
            return m_map[k];
        }

    private:
        std::mutex m_mutex;
        std::map<int, std::string> m_map;
};

int main (int argc, char *argv[]) {
    Cache c;
    auto v = c[42];
    std::cout << v << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如我所看到的那样,我的意图是并发性,并且在释放互斥锁之后,不能保证映射值的继续存在.

std::map<>::operator[]返回一个引用std::string&.我的理解是,复制结构会产生一个无名的临时版,然后可能会受到RVO的影响.

何时会发生复制省略,这是否会导致不同的线程返回相同的对象而不是自己的副本?如果是这样,怎么能避免这种情况?

实际代码涉及数据库查找填充缓存,其中映射键是表主键,映射值是从行字段构造的对象.

c++ concurrency stl thread-safety

7
推荐指数
1
解决办法
257
查看次数

标签 统计

c++ ×1

concurrency ×1

stl ×1

thread-safety ×1