簡體   English   中英

為什么C ++允許類型為std :: map而沒有默認構造函數而不是std :: pair?

[英]Why does C++ allow type has no-default constructor for std::map while not std::pair?

檢查以下C++代碼:

#include <string>
#include <map>

class A
{
public:
    A (int a) {};
};

int main()
{

    std::map<std::string, A> p;
    return 0;
}

編譯成功。 std::map更改為std::pair

#include <string>
#include <utility>

class A
{
public:
    A (int a) {};
};

int main()
{

    std::pair<std::string, A> p;
    return 0;
}

編譯器會抱怨:

$ clang++ test.cpp
In file included from test.cpp:1:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/string:40:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/char_traits.h:39:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/stl_algobase.h:64:
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/7.3.0/../../../../include/c++/7.3.0/bits/stl_pair.h:219:18: error: no matching
      constructor for initialization of 'A'
      : first(), second() { }
                 ^
test.cpp:13:31: note: in instantiation of member function 'std::pair<std::__cxx11::basic_string<char>, A>::pair'
      requested here
    std::pair<std::string, A> p;
                              ^
test.cpp:7:5: note: candidate constructor not viable: requires single argument 'a', but no arguments were provided
    A (int a) {};
    ^
test.cpp:4:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were
      provided
class A
      ^
1 error generated.

為什么C++允許類型為std::map而沒有默認構造函數而不是std::pair

構造時std::map為空,這意味着它不需要構造A 另一方面, std::pair必須這樣做才能完成初始化。

由於兩者都是類模板,因此實際上只實例化了您使用的成員函數。 如果要查看預期的錯誤,則需要讓映射嘗試構造默認A ,例如:

int main()
{
    std::map<std::string, A> p;

    p[""];
}

差異是由於A不是默認構造的。 對案例立即選擇它,因為它將嘗試默認構造A實例。

最終地圖案例將產生相同的錯誤。 如果你寫p["Hello"];你可以看到這個p["Hello"];

int main()
{
    std::map<std::string, A> p;
    p["Hello"]; // oops - default constructor required here for `A`
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM