【发布时间】:2021-01-11 09:13:46
【问题描述】:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class x{
public:
string s;
//x(){cout<<"default"<<endl;}
x(string s=""):s(s){cout<<"mine"<<endl;}
};
int main()
{
map<int,x> m;
m.insert(pair<int,x>(1,x("me")));
cout<<m[1].s<<endl;
}
我知道当元素不存在时 map::operator[] 需要默认 cst,但是
m[1] 在没有默认 cst 的情况下为苹果 clang 中的 x 类给出错误,即使 m[1] 的元素已经存在。为什么?
【问题讨论】:
-
这就是静态检查的工作原理。
-
编译器如何知道现有元素?
-
使用
at:m.at(1).s不需要默认ctor -
为了在编译时确定对象存在,编译器需要执行程序,但不先编译就不可能执行程序。
-
@fas 是 map::at c++11 的特性吗?
标签: c++ dictionary default-constructor