简体   繁体   English

将本地变量存储在STL容器中的类中是否安全?

[英]Is storing a local variable in an STL Container in a class safe?

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
}

Now, is this code safe? 现在,此代码安全吗? Basically, does MyMap store a copy of my_img when I insert it, or does it store a reference ? 基本上,当我insert my_img时, MyMap存储MyMap副本还是存储引用

It will store a copy. 它将存储一个副本。

However, do you really need inheritance? 但是,您真的需要继承吗? You should make the std::map a class member. 您应该使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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM