简体   繁体   中英

error C2248: 'X::operator =' : cannot access private member declared in class 'X'

Similar questions are already asked on stackoverflow. I do have looked at them but still unable to resolve the issue I am facing

I have a structure X with few member variables including a mutex . I am using this mutex to lock access to member vector called vecIds when pushing elements in it from multiple threads.

Further, as I donot want objects of type X to be copyable or copy constructable, I declare copy constructor and copy assignment operator functions as private

struct X
{
    bool a;
    unsigned value;
    std::vector<unsigned> vecIds;
    std::mutex mutex;

    X(): a(false), value(0), mutex(){}

 private:
    X( X const &x);
    X& operator=( Xconst &x);
 };

Somewhere in my code I am creating vector of 100 objects of type X. When I compile my code I see the following errors:

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\xutility(2466): error C2248: 'X::operator =' : cannot access private member declared in class 'X'
X.h(12): see declaration of 'X::operator ='    
X.h(2): see declaration of 'X'

I donot seem to figure out where is the problem

This is a VS2012 bug fixed in VS2013. VS2012's implementation of

explicit vector(size_type n);

calls resize() , which requires the element to be both DefaultInsertable and MoveInsertable . This is nonconforming, since the constructor itself only requires DefaultInsertable * . (To make it worse, its resize() implementation calls erase() , which requires the type to be MoveAssignable ...)

It's mentioned in this MSDN blog post (search for " vector<DefaultConstructible>(10) ").

If you are using a fixed-length container, consider using a std::array<X, 100> .


* When the default allocator is used, the *Insertable requirements basically translate to *Constructible .

Your code compiles fine in VS2013, to resolve your problem in a quick way, try a vector of smart pointers

#include <memory>

std::vector<std::unique<X>> x(100);

Note: your struct X has std::mutex as member, mutex is not copyable nor moveable, which means X is nonCopyable nor moveable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM