Public Operator New, Private Operator Delete: Getting C2248 "Can Not Access Private Member" When Using New

Public operator new, private operator delete: getting C2248 can not access private member when using new

When you do new Foo() then two things happen: First operator new is invoked to allocate memory, then a constructor for Foo is called. If that constructor throws, since you cannot access the memory already allocated, the C++ runtime will take care of it by passing it to the appropriate operator delete. That's why you always must implement a matching operator delete for every operator new you write and that's why it needs to be accessible.

As a way out you could make both of them private and invoke operator new from a public member function (like create()).

Concurrency::critical_section build error: cannot access private member

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 &)'

error C2248: 'klientPracownik::klientPracownik' : cannot access private member declared in class 'klientPracownik'

Your klientPracownik class is missing public: -- which means all its members / methods are private (even its constructor).



Related Topics



Leave a reply



Submit