3 ms·
I'm not 100% certain whether I like this. Consider the following concurrent pseudo-code: class A { public: void add () { // <locking happens he
by stingraycharles 16y ago
I'm not 100% certain whether I like this. Consider the following concurrent pseudo-code:
class A {
public:
void add () {
// <locking happens here>
_v += "foo";
}
std::string const get () {
// <locking again>
return _v;
}
private:
std::string _v;
};
Now, if I launch multiple threads that call get () and add () at the same time, normally this would be thread-safe, if locking occurs. However, if I understood it correctly, get () can also return by reference, since it is const.
Wouldn't this create race conditions?
- tbrownaw 16y agoNo. If your function does "return <some local var>", as in Foo xyzzy() { Foo ret; /* do stuff to ret */ return ret; } then the compiler can rewrite it to be something like void xyzzy(void * _ptr) { Foo * _ret = new(_ptr)Foo(); /* do stuff to *_ret */ } where the function-local variable that gets returned is actually just constructed in the place that it would eventually be returned/copied to and so doesn't have to be returned at all.
- pdovy 16y agoThis would introduce another performance consideration though, wouldn't it? You may not be paying the cost for the explicit copy, but now you are paying the cost of allocating space for a Foo on the heap instead of the stack. It would depend on the situation, but this seems like it might just be wash at the end in terms of performance?
- 124816 16y agoThat weird new(T* )T(...) syntax is how you ask c++ to run the constructor of T on an existing T* . (In this case that T* would point to the stack.) Note that the memory at the T* shouldn't be a real T; or if it is, its destructor ought to be run first.