c++ - 将局部变量存储在类的 STL 容器中安全吗?

标签 c++ variables stl dictionary containers

class MyMap : std::map<char, pro::image>
{
public:
     void MyMethod(char x);
     /** code **/
}

void MyMap::MyMethod(char x)
{
     pro::image my_img; // note that my_img is a local variable
     my_img.LoadFromFile("my_image.png");

     this->insert(std::pair<char, pro::image>(x, my_img)); // stored in the class
}

现在,这段代码安全吗?基本上,当我插入时,MyMap是否存储my_img拷贝,还是存储my_img拷贝引用?

最佳答案

它将存储一个拷贝。

但是,你真的需要继承吗?您应该使 std::map 成为类成员。

class MyMap
{
    std::map<car, pro::image> map_;
public:
     void MyMethod(char x);
     /** code **/
};

void MyMap::MyMethod(char x)
{
     pro::image my_img; // note that my_img is a local variable
     my_img.LoadFromFile("my_image.png");

     map_.insert(std::pair<char, pro::image>(x, my_img)); // stored in the class
}

关于c++ - 将局部变量存储在类的 STL 容器中安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11380460/

相关文章:

c++ - 我在哪里可以下载到 GNU C++ 标准库的源代码?

c++ - std::list 元素分配在哪里?

c++ - 如何在不调用复制构造函数的情况下使用类初始化 STL vector/列表

r - 创建新变量

html - SCSS 引用元素的特定实例

c++ 组 2 个或多个字符串作为一个输入

c++ - C++上的 vector 迭代器

c++ - 哪种设计模式最合适?

c++ - vector 中 N 个最小值的索引

c++ - std::map 查找不能正常工作