友元类不能调用私有构造函数

Mac*_*Mac 2 c++ c++11

下面的代码是我今天正在使用的东西的简化版本。它有 2 个类 A 和 B。 B 类尝试使用 A 类的私有构造函数,但失败了。如果我将构造函数公开,则代码编译得很好。这是为什么?

#include <vector>

class A
{
friend class B;
private:
    A(int * int_ptr) {
        m_int = *int_ptr;
    }
private:
    int m_int;
};


class B
{
friend class A;
public:
    static void create_vec_a() {
        int v1(1);
        int v2(2);

        std::vector<int *> int_ptr_vec{
            &v1,
            &v2
        };

        std::vector<A> a_vec(int_ptr_vec.begin(),
            int_ptr_vec.end());
    }
};

int  main(int argc, char *argv[])
{
    B::create_vec_a();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在 Visual Studio 中得到的错误是:

'A::A': cannot access private member declared in class 'A'
Run Code Online (Sandbox Code Playgroud)

在叮当上:

test.cpp:28:18: note: in instantiation of function template specialization 'std::vector<A, std::allocator<A> >::vector<__gnu_cxx::__normal_iterator<int **, std::vector<int *, std::allocator<int *> > >, void>' requested here
            std::vector<A> a_vec(int_ptr_vec.begin(),
                           ^
test.cpp:7:2: note: declared private here
    A(int * int_ptr) {
    ^
Run Code Online (Sandbox Code Playgroud)

Voi*_*tar 7

您必须使用朋友std::allocator<A>;,因为那是试图访问构造函数的人。

class A
{
    friend class std::allocator<A>;
...
Run Code Online (Sandbox Code Playgroud)

尽管从给定的示例中很难对整体设计发表评论,但我会考虑将其公之于众,因为class A如果 stl 可以,任何可以看到它的人都可以构建它。