Reputation: 62797
Code:
class Data {
const QString qs; // const here is the point of the question
public:
Data(const QString &s) : qs(s) {}
QString getter() const { return qs; } // mutex needed?
const QString &rgetter() const { return qs; } // not thread-safe at all?
}
The getter methods are called from multiple threads for same Data
object, un-synchronized.
Now documentation says, emphasis mine:
You can safely access different instances of QString from multiple threads simultaneously, but you can't safely access the same instance of QString from multiple threads simultaneously (unless you protect the accesses yourself with a QMutex).
However, in general in C++, when just reading const
objects from multiple threads, mutex is not needed. There's the Copy-on-Write mechanism in the background after all, so does taking a copy of a const QString
constitute the kind of access that is forbidden by the Qt doc quote above?
Does getter()
method above need a mutex to return a copy of qs
, and is the const
reference returned by rgetter()
never really safe in multi-threaded context?
If above code is broken for multi-threading, would this be a safe alternative?
class Data {
const std::string ss; // will contain UTF-8
public:
Data(const QString &s) : ss(s.toStdString()) {}
QString getter() const { return QString::fromStdString(ss); }
}
Upvotes: 1
Views: 242
Reputation: 29985
In your sample, your member variable is const
, that means you are guaranteed it is not mutated anywhere. Considering that, you can hand people const references to this variable or copies, and both are thread-safe.
class Data {
const QString qs;
public:
Data(const QString &s) : qs(s) {}
QString getter() const { return qs; } // Safe, no life-time management needed
const QString &rgetter() const { return qs; } // Safe, but you must make sure Data outlives the references.
}
Upvotes: 1