For those who do not know what RAII is, you are probably using it without knowing it. One common use of this C++ idiom is to keep code manipulating mutexes exception safe. While I was writing a thread safe getter with a scoped lock like this:
A B::getA() const { ScopedLock sc(m_lock); return m_a; }
A doubt sparkled in my mind about whether or not the object copy performed by the return statement was protected by the lock. It must be since I have seen tons of functions using similar pattern but I could not explain why. I asked to another senior developer and he could not tell neither. By the way, this is what I love about the C++ language. You can have years of experience with it, there are millions of small details and any day, you may stumble on a mind boggling detail that force you to stop and think about it.
So if we come back to the original question, I guess that I could have checked what the standard document says about it but it is boring to do so. I prefer to do small scientific experiments to figure out myself what is the answer. So I wrote this small program:
#include <iostream> class RAIIObj { public: RAIIObj() { std::cout << "RAIIObj()\n"; } ~RAIIObj() { std::cout << "~RAIIObj()\n"; } }; class A { public: A() {} A( const A & ) { std::cout << "A( const A & )\n"; } }; class B { public: B() {} A getSyncAByVal() const; private: A m_a; }; A B::getSyncAByVal() const { RAIIObj scopedLock; return m_a; } int main( int argc, char *argv[] ) { B b; A retVal = b.getSyncAByVal(); return 0; }
and here is the output confirming that the getter code is correct:
RAIIObj() A( const A & ) ~RAIIObj()
Now that I know the answer, I have found another proof confirming that return statement object copies are performed before the local lock goes out of scope. If you were returning by value a local object, it absolutely must be copied before going out of scope.
No Comments/Pingbacks for this post yet...
This post has 8 feedbacks awaiting moderation...
Comments are closed for this post.
I want you to find in this blog informations about C++ programming that I had a hard time to find in the first place on the web.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
<< < | > >> | |||||
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |