C++ 为什么可以';设置函数参数的默认值<;地图>;类型?

C++ 为什么可以';设置函数参数的默认值<;地图>;类型?,c++,C++,下面是我的示例程序,它不会编译。我想创建一个函数,该函数将map作为可能的参数,但如果没有提供,则提供默认的空map。非常直截了当,只是不知道为什么它不起作用 #include <map> #include <iostream> using std::cout; using std::endl; using std::map; int func(map<int, int>& = map<int, int>()); int main()

下面是我的示例程序,它不会编译。我想创建一个函数,该函数将map作为可能的参数,但如果没有提供,则提供默认的空map。非常直截了当,只是不知道为什么它不起作用

#include <map>
#include <iostream>
using std::cout; using std::endl; using std::map;

int func(map<int, int>& = map<int, int>());

int main() {
    map<int, int> m;
    m[2] = 4;

    cout << "func() = " << func() << endl;   // "func() = 0"
    cout << "func(m) = " << func(m) << endl; // "func(m) = 1"
}

int func(map<int, int>& m) { return m.size(); }
#包括
#包括
使用std::cout;使用std::endl;使用std::map;
int func(map&=map());
int main(){
地图m;
m[2]=4;

cout您可以用常量引用绑定临时对象。因此函数可以声明为

int func( const map<int, int>& = map<int, int>());
int-func(const-map&=map());

在本例中,这是可行的。在我打算使用它的地方,我实际上是在函数内部向映射添加值,然后返回一个副本。假设函数是
map func(map&m){m[3]=6;return m;}
。将常量添加到参数中会导致此操作失败。我想我可以执行
map func(const map&m){map mm=m;mm[3]=6;return mm;}
但这需要额外的不必要副本(mm=m并返回mm),而不仅仅是(return m)。
int func( const map<int, int>& = map<int, int>());