Search code examples
c++pplconcurrency-runtime

Concurrency::critical_section build error: cannot access private member


I can't build below code(vs2013) blocks and getting error "error C2248: 'Concurrency::critical_section::critical_section' : cannot access private member declared in class 'Concurrency::critical_section'"

Anyone can help explain why this is happening? Thanks

#include <ppl.h>

class Class1{

public: 

    concurrency::critical_section _cs;
    int f1;
    Class1(int f){ f1 = f; }
};

class Class2{

public: 
    std::vector<Class1> v1;
    Class2(){ v1.push_back(Class1(1)); v1.push_back(Class1(2)); }
};

int _tmain(int argc, _TCHAR* argv[])
{    
    Class2 c2();

    return 0;
}

Solution

  • concurrency::critical_section is neither copyable nor movable (this was done in the old-fashioned way of making its copy constructor private, hence the error you get). Therefore, Class1 as written cannot be copied or moved either, and you can't push_back it into a vector.

    To fix this, you can write your own copy constructor and copy assignment operator that copies only f1:

    class Class1
    {
    public: 
            concurrency::critical_section _cs;
            int f1;
            Class1(int f) : f1(f) { }
            Class1(const Class1 &other) : f1(other.f1) { }
            Class1 & operator=(const Class1 &other) { 
                // synchronization omitted
                f1 = other.f1;
            }
    };
    

    Side note: Class2 c2(); declares a function returning a Class2, not a value-initialized object.

    Side note 2: The error messages in VS's "Error List" are generally incomplete. You'll want to check the Build Output for the full error log. In this case, the full error log on my VS2013 is:

    ConsoleApplication2.cpp(15): error C2248: 'Concurrency::critical_section::critical_section' : cannot access private member declared in class 'Concurrency::critical_section'
              D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\concrt.h(3712) : see declaration of 'Concurrency::critical_section::critical_section'
              D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\concrt.h(3549) : see declaration of 'Concurrency::critical_section'
              This diagnostic occurred in the compiler generated function 'Class1::Class1(const Class1 &)'