Initializing a reference with curly braces vs parentheses

35 views Asked by At

I came across an issue which surprised me. I though that

int i = 3;
int i {3};
int i (3);

were equivalent.

This lead me to do (please note the t {t_} in the constructor) for the following class (exampel from Anthony Williams book C++ Concurrency in Action, so giving creds here so I don't violate some copyright issue):

class thread_guard{
    std::thread& t;
public:
    explicit thread_guard(std::thread& t_) : t {t_} {}
    ~thread_guard()
    {
        if(t.joinable())
            t.join();
        std::cout << "~thread_guard running" << std::endl;
    }
};

This gives me a compiler error:

error: invalid initialization of non-const reference of type 'std::thread&' from an rvalue of type...

However, changing the

t {t_}

into

t (t_)

makes it work. This of course makes me question my assumption of equivalance between the two.

Thank you for any input.

Edit: Compiler is g++, version 4.8.1 on Windows 8.1.

0

There are 0 answers