On 7/18/2026 8:25 AM,
boltar@caprica.universe wrote:
On Sat, 18 Jul 2026 17:58:16 +0300
Paavo Helde <eesnimi@osa.pri.ee> gabbled:
On 7/18/2026 12:19 PM, boltar@caprica.universe wrote:
Is this function thread safe? Ie will the return string value be set on
the stack before the lock_guard is released?
string mygetter(void)
{
˙˙˙˙lock_guard<mutex> lock(setmtx);
˙˙˙˙return some_string_set_elsewhere;
}
or do I need to do this:
string mygetter(void)
{
˙˙˙˙lock_guard<mutex> lock(setmtx);
˙˙˙˙string tmp = some_string_set_elsewhere;
˙˙˙˙return tmp;
}
I should probably know the answer to this but I'm not 100% sure.
AFAIK these are functionally equivalent and the compiler can optimize
them to the same machine code. To my knowledge, both are safe (the
return value is constructed before destroying local variables like lock).
Thanks. That is certainly the sensible approach but you can never be 100% sure with C++.
You can see it in action by making a raii object cout what its doing. Something like this:
_____________________
#include <iostream>
struct raii
{
raii()
{
std::cout << "(" << this << ")->raii::raii()\n";
}
~raii()
{
std::cout << "(" << this << ")->raii::~raii()\n";
}
};
struct raii_return
{
int m_state = 0;
raii_return(int state) : m_state(state)
{
std::cout << "(" << this << ")->raii_return::raii_return()
m_state = " << m_state << "\n";
}
~raii_return()
{
std::cout << "(" << this << ")->raii_return::~raii_return()
m_state = " << m_state << "\n";
}
};
raii_return
foo()
{
raii raii0;
std::cout << "foo()\n";
return raii_return(42);
}
int main()
{
std::cout << "before foo()\n";
foo();
std::cout << "after foo()\n";
return 0;
}
_____________________
Gives me this output, examine it:
_____________________
before foo()
(0x7fffd424560f)->raii::raii()
foo()
(0x7fffd424563c)->raii_return::raii_return() m_state = 42 (0x7fffd424560f)->raii::~raii()
(0x7fffd424563c)->raii_return::~raii_return() m_state = 42
after foo()
_____________________
It works fine.
--- PyGate Linux v1.5.18
* Origin: Dragon's Lair, PyGate NNTP<>Fido Gate (3:633/10)