Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Guarding a thread

19 views
Skip to first unread message

Paul

unread,
Jan 28, 2017, 8:08:44 PM1/28/17
to
The code below is copied from a blog. Should the author have said
Guard(const Guard& other)=delete;

Does the const omission matter? I would have thought that the author's
code doesn't prevent copying. The version without the const is a different
function.

Paul



#include <iostream>
#include <thread>

class Guard
{
public:
Guard(std::thread& t)
: thread(t)
{ }

~Guard()
{
if (thread.joinable())
{
thread.join();
}
}

Guard(Guard& other)=delete;
Guard& operator=(const Guard& rhs)=delete;

private:
std::thread& thread;
};

void function()
{
std::cout << "I'm inside function." << std::endl;
}

int main()
{
std::thread t(function);
Guard guard(t);

return 0;
}

Alf P. Steinbach

unread,
Jan 28, 2017, 9:12:17 PM1/28/17
to
On 29.01.2017 02:08, Paul wrote:
> The code below is copied from a blog. Should the author have said
> Guard(const Guard& other)=delete;
>
> Does the const omission matter? I would have thought that the author's
> code doesn't prevent copying. The version without the const is a different
> function.
>
> #include <iostream>
> #include <thread>
>
> class Guard
> {
> public:
> Guard(std::thread& t)
> : thread(t)
> { }
>
> ~Guard()
> {
> if (thread.joinable())
> {
> thread.join();
> }
> }
>
> Guard(Guard& other)=delete;
> Guard& operator=(const Guard& rhs)=delete;
>
> private:
> std::thread& thread;
> };
>
> void function()
> {
> std::cout << "I'm inside function." << std::endl;
> }
>
> int main()
> {
> std::thread t(function);
> Guard guard(t);
>
> return 0;
> }
>

In the formal there are four possible “copy” constructors: T(T&), T(T
const&), T(T volatile& ) and T(T const volatile&). Declaring any of them
prevents the automatic generation of a “copy constructor”.


Cheers!,

- Alf

0 new messages