Returning QReadLocker by value from a function?
-
Hi, I have a class where I use a
QReadWriteLock
to protect access to its data while reading and writing. Since the class has to emit signals when its data changes, I have made theQReadWriteLock
private and only provided read-locking (lockForRead()
,tryLockForRead(int timeout)
, andunlock()
) access in its public interface. I would also like to provide aQReadLocker
access to this lock, I am wondering if this is the correct way to provide that access:.h file
class MyData : public QObject { Q_OBJECT public: QReadLocker getLocker(); private: QReadWriteLock lock; }
.cpp file
QReadLocker MyData::getLocker() { return QReadLocker{&lock}; }
I have tested it in a simple class and it seems to work fine. But I am not 100% sure if this would hold in real-world usage because of the confusion about copy and move constructors when returning an object by value from a function in C++. Are there any downsides to providing
QReadLocker
object as a return value from a function? -
Hi, I have a class where I use a
QReadWriteLock
to protect access to its data while reading and writing. Since the class has to emit signals when its data changes, I have made theQReadWriteLock
private and only provided read-locking (lockForRead()
,tryLockForRead(int timeout)
, andunlock()
) access in its public interface. I would also like to provide aQReadLocker
access to this lock, I am wondering if this is the correct way to provide that access:.h file
class MyData : public QObject { Q_OBJECT public: QReadLocker getLocker(); private: QReadWriteLock lock; }
.cpp file
QReadLocker MyData::getLocker() { return QReadLocker{&lock}; }
I have tested it in a simple class and it seems to work fine. But I am not 100% sure if this would hold in real-world usage because of the confusion about copy and move constructors when returning an object by value from a function in C++. Are there any downsides to providing
QReadLocker
object as a return value from a function?@CJha said in Returning QReadLocker by value from a function?:
Are there any downsides to providing QReadLocker object as a return value from a function?
Yes. It won't work. semaphores are special kinds of objects. By design, they should never be copied.
Take simple counting semaphore. the count indicates whether a resource can acquire it. They are usually nothing more than an integer that is guaranteed atomic access. when you copy the integer the references are still to the old object, not the new one.
On a larger note, I think your whole model is kind of flawed. Don't "wrap" semaphores. Therein lies the introduction of race conditions. Use a reference to the sole instance of a semaphore anywhere it is needed.