我遇到了这个示例类 http://www.boost.org/doc/libs/1_49_0/libs/smart_ptr/sp_techniques.html#as_lock我正在为语法而苦苦挣扎。
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)) {}
};
我(相信我)理解除了“(m.lock(), &m)”这部分以外的所有内容。整个事情似乎是初始化智能指针的第一个参数。该复合语句的计算结果是什么?它只是m的地址吗?为什么把锁作为参数列表的一部分放在那里(它是如何合法的)?相反,我会期待这样的声明:
template<class Mutex> explicit shared_lock(Mutex & m): pv(&m, mem_fn(&Mutex::unlock)) {m.lock();}
我的替代语句是否改变了功能?
最佳答案
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)?
构造函数需要获取锁,这是放置它的一个方便的地方。否则必须在构造函数的主体中设置共享指针。
这是合法的,因为在初始化程序中使用了表达式,包括逗号运算符。需要额外的括号来消除逗号运算符与逗号分隔参数的歧义,但除此之外,大多数任何表达式都是允许的。
关于c++ - 参数语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11233447/