stl map <char*,char*>析构函数

Bob*_*ait 5 c++ stl

我知道map析构函数会调用每个包含元素的析构函数.会发生什么事

map<char*,char*> ?
Run Code Online (Sandbox Code Playgroud)

我无法在/usr/include/c++/4.4中看到此代码的位置


编辑:我应该说

map<const char*, const char*, ltstr>
Run Code Online (Sandbox Code Playgroud)

http://www.sgi.com/tech/stl/Map.html

Joh*_*ing 13

当a map<char*,char*>被销毁时,它所包含的所有元素也是如此.如果它是类类型,则调用每个元素的析构函数.

但是,请记住上面地图中包含的内容.它不是字符串,正如您所期望的那样 - 它只是指向字符串的指针.字符串本身不会被破坏.只有指针. delete永远不会被指针调用.

例证:

map<char*, char*> strings;

char* key = new char[10];
char* value = new char[256];
/* ... */
strings.insert(key,value);
Run Code Online (Sandbox Code Playgroud)

在上面,由于delete从未调用由调用创建的指针new,因此当strings超出范围时,此内存将泄漏.

这是一个很好的例子,说明为什么你应该避免使用原始指针,newdelete.在你的情况下,map<string,string>可能是一个更好的选择.

编辑:

正如@sbi在评论中提到的那样,你想要map<string,string>结束的另一个原因map<char*,char*>是因为map<string,string>键是按值而不是按指针值进行比较.

考虑:

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

int main()
{
    static const char MyKey[] = "foo";
    const char bar[] = "bar";
    typedef map<const char*,const char*> Strings;
    Strings strings;
    strings.insert(make_pair(MyKey,bar));

    string ss = "foo";
    Strings::const_iterator it = strings.find(ss.c_str());
    if( it == strings.end() )
        cout << "Not Found!";
    else
        cout << "Found";

}
Run Code Online (Sandbox Code Playgroud)

从根本上说,您要插入一个带有"foo"键的元素,然后搜索该元素.测试上面的代码,你会发现它找不到.但是,如果您尝试这样做:

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

int main()
{
    typedef map<string,string> Strings;
    Strings strings;
    strings.insert(make_pair("foo","bar"));

    string ss = "foo";
    Strings::iterator it = strings.find(ss);
    if( it == strings.end() )
        cout << "Not Found~!";
    else
        cout << "Found";
}
Run Code Online (Sandbox Code Playgroud)

......你得到了你真正想要的行为.

  • 很好的答案,"+ 1"来自我.更喜欢`std :: string`的另一个原因是在`std :: map <char*,T>`中,键将被_address_而不是_content_进行比较.你很少想要那个. (2认同)

Sig*_*erm 6

怎么了

没有.如果你动态分配内存,它会泄漏 - 没有自动析构函数char*.

使用std::string或类似的类.

  • 我认为_technically_它有一个不做任何事情的析构函数.(你可以调用`A-> ~char*()`)但效果是一样的. (2认同)