Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter syntax

Tags:

c++

syntax

I came across this example class http://www.boost.org/doc/libs/1_49_0/libs/smart_ptr/sp_techniques.html#as_lock and I'm struggling with the syntax.

class shared_lock
{

private:

    shared_ptr<void> pv;

public:

    template<class Mutex> explicit shared_lock(Mutex & m): pv((m.lock(), &m), mem_fn(&Mutex::unlock)) {}
};

I (believe I) understand everything except this part "(m.lock(), &m)". That entire thing appears to be the first parameter to initialize the smart pointer. What does that compound statement evaluate to? Is it simply the address of m? Why is the lock placed there as part of the parameter list (and how is it legal)? Instead, I would have expected a statement like:

template<class Mutex> explicit shared_lock(Mutex & m): pv(&m, mem_fn(&Mutex::unlock)) {m.lock();}

Does my alternate statement change the functionality?

like image 756
helmk Avatar asked May 06 '26 04:05

helmk


1 Answers

What does that compound statement evaluate to? Is it simply the address of m?

Yes

Why is the lock placed there as part of the parameter list (and how is it legal)?

The constructor needs to acquire the lock and it that's a conveinent place to put it. otherwise the shared pointer would have to be set in the constructor's body.

It's legal because expressions, including the comma operator, are used in initializers. The extra parentheses are needed to disambiguate the comma operator from the comma separating parameters, but otherwise most any expression is allowed.

like image 163
bames53 Avatar answered May 11 '26 03:05

bames53



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!