c++ - 为什么 C++ 允许 std::map 的类型没有默认构造函数,而 std::pair 则不允许?

标签 c++

检查以下 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 必须这样做才能完成其初始化。

由于两者都是类模板,所以只有你使用的成员函数才真正被实例化。如果你想看到你期望的错误,你需要让 map 尝试构造一个默认的 A,例如:

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

    p[""];
}

关于c++ - 为什么 C++ 允许 std::map 的类型没有默认构造函数,而 std::pair 则不允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49231881/

相关文章:

c++ - boost 共享内存 : the volume of a file has been externally altered and open file is not longer valid

c++ - 为什么 make_shared 在单独的调用中分配相同的地址?

c++ - Cloud9 C++ 断点

c++ - 本地主机上的最大连接数

c++ - 可变函数通用哨兵值

c++ - "boolean short circuiting"是由标准规定的还是仅用作优化?

c++ - 将额外值传递给 GTK+ 中的信号

c++ - 在成对 vector 中,找到第一个值等于 X 的对并返回第二个值,或者返回 Y

c++ - QT OpenGL无法完全渲染立方体吗?

c++ - 重载新运算符时,它不会为 char 指针分配内存