问题
This really feels like a bug in Qt. Anyone has a solution or should I file it as a bug?
#include <QReadWriteLock>
class FileInfoWrapper {
public:
explicit FileInfoWrapper(const QFileInfo& _fileInfo);
~FileInfoWrapper();
private: // also tried public
mutable QReadWriteLock lock_;
Before even using it, I get the error:
Error 1 error C2248: 'QReadWriteLock::QReadWriteLock' : cannot access private member declared in class 'QReadWriteLock'
Doesn't matter if it's private/public or what classes I include. I don't seem to be able to create it on the stack. Instead I created one on the heap using 'new', but when I try to delete it in the constructor my application crashes with:
Unhandled exception at 0x5090f39a (QtCored4.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0xfeeeff0e.
Call stack:
QtCored4.dll!QHash::~QHash() Line 283 + 0xa bytes C++ QtCored4.dll!QReadWriteLockPrivate::~QReadWriteLockPrivate() + 0x38 bytes C++ QtCored4.dll!QReadWriteLockPrivate::`scalar deleting destructor'() + 0xf bytes C++ QtCored4.dll!QReadWriteLock::~QReadWriteLock() Line 137 + 0x1e bytes C++ CloudSync.exe!FileInfoWrapper::~FileInfoWrapper() Line 76 + 0x15 bytes C++
The variable 'd' in QReadWriteLockPrivate seems to be deleted twice. However, this works in another class where I also had to create the lock on the heap and then delete it in the constructor.
Running Qt 4.8.0 in Visual Studio. Had the same issue in Qt creator 4.7.4.
回答1:
You have to use a pointer because QReadWriteLock
is not copyable (it uses Q_DISABLE_COPY
) and you are somehow copying your FileInfoWrapper
objects (by storing them in a container for example).
So the pointer address is shared between those copies, and deleted once for each copy.
You can wrap the pointer inside a smart pointer, so that deletion will only occur when the last copy of your object is deleted.
QSharedPointer<QReadWriteLock> lock_;
来源:https://stackoverflow.com/questions/9507604/cannot-access-private-member-declared-in-class-qreadwritelockerror1error-c22