map >和map >有什么区别?

map <string,pair <string,foo * >>和map <string,pair <string,foo&>>有什么区别?

问题描述:

我写了一个抽象类foo,并且bar类从foo继承。map <string,pair <string,foo * >>和map <string,pair <string,foo&>>有什么区别?

我想创建一个地图容器,它是map<string, pair<string, foo&>>,但我无法成功编译。编译器告诉我

“std::pair<std::string,foo &>::pair”: not appropriate default constructor 

这里是代码:

#include <iostream> 
#include <string> 
#include <windows.h> 
#include <map> 
#include <utility> 

using namespace std; 

class foo 
{ 
public: 
    virtual void t() = 0; 
}; 

class bar :public foo 
{ 
public: 
    void t() 
    { 
     cout << "bar" << endl; 
    } 
}; 

int main() 
{ 
    bar b; 
    //wrong 
    //map<string, pair<string, foo&>> t; 
    //pair<string, foo&> p("b", b); 
    //t["t"] = p; 

    //right 
    map<string, pair<string, foo*>> t; 
    pair<string, foo*> p("b", &b); 
    t["t"] = p; 
    p.second->t(); 
} 

我想知道map<string, pair<string, foo*>>map<string, pair<string, foo&>>之间的差异。

+5

你知道指针和引用之间有什么不同吗? – NathanOliver

+2

https://*.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in –

+0

@FrançoisAndrieux您能否详细解释一下原因? – lens

第一个示例(您标记为“错误”)的问题是行t[" t"] = p;。如果你看一下文档std::map::operator[]你会发现下面的一段话:

  • VALUE_TYPE必须是从的std :: piecewise_construct,性病:: forward_as_tuple(键),性病::元组<>()EmplaceConstructible。

这意味着你的mapped_type(在这种情况下,foo&)必须是缺省构造的。但是,引用必须是总是引用一个现有的对象,它们不能被默认构造。使用指针的例子很好,因为指针没有这个限制。

您可以使用引用作为mapped_type,但您必须避免operator[]。例如,您可以找到一个带有std::map::find的元素或使用std::map::emplace插入一个元素。下面的例子编译得很好:

#include <string> 
#include <map> 
#include <utility> 

using namespace std; 

struct foo {}; 

int main() 
{ 
    foo b; 
    //wrong 
    map<string, pair<string, foo&>> t; 
    pair<string, foo&> p("b", b); 
    t.emplace("t", p); 
}