2012-07-08 59 views
2
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当我insert它,还是它存储参考是否将一个本地变量存储在类安全的STL容器中?

+3

这很安全。然而,std :: map有一个非虚拟的析构函数,所以你不应该从它继承。 – mfontanini 2012-07-08 03:37:54

+2

这只与'pro :: image'的复制构造函数一样安全。如果不能安全地复制'pro :: image',比'std :: map '不安全。 – 2012-07-08 03:44:24

回答

5

它会存储一个副本。

但是,你真的需要继承吗?你应该让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 
} 
+0

[这个页面](http://www.cplusplus.com/reference/unordered_map/unordered_map/insert/)说如果你改用'map_.insert(std :: make_pair(x,my_img))'的形式,那么它将“移动元素(即,val将丢失其内容,这是由容器中的新元素获得的)”。这是不安全的,因为my_img是一个自动变量?或者,C++足够智能,不会尝试移动存储在自动变量中的数据? – 2014-01-30 22:52:30

+0

@BrianGordon:数据移动是安全的,因为临时结束会破坏已移动到其位置的默认初始化对象。 – jxh 2014-01-31 01:36:14

相关问题