How does scoped_lock avoid emitting an quot;unused variablequot; warning?(scoped_lock 如何避免发出“未使用的变量?警告?)
问题描述
boost::mutex::scoped_lock
是一个方便的 RAII 包装器,用于锁定互斥锁.我对其他事情使用了类似的技术:一个 RAII 包装器,它要求数据接口从/重新连接到串行设备.
boost::mutex::scoped_lock
is a handy RAII wrapper around locking a mutex. I use a similar technique for something else: a RAII wrapper around asking a data interface to detach from/re-attach to a serial device.
但是,我想不通的是为什么在下面的代码中只有我的对象 mst
—其实例化和销毁确实有副作用 —导致 g++
发出未使用变量"警告错误,而 l
设法保持沉默.
What I can't figure out, though, is why in the code below only my object mst
— whose instantiation and destruction do have side effects — causes g++
to emit an "unused variable" warning error whereas l
manages to remain silent.
你知道吗?你能告诉我吗?
Do you know? Can you tell me?
[generic@sentinel ~]$ cat test.cpp
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <iostream>
struct MyScopedThing;
struct MyWorkerObject {
void a() { std::cout << "a"; }
void b() { std::cout << "b"; }
boost::shared_ptr<MyScopedThing> getScopedThing();
};
struct MyScopedThing {
MyScopedThing(MyWorkerObject& w) : w(w) {
w.a();
}
~MyScopedThing() {
w.b();
}
MyWorkerObject& w;
};
boost::shared_ptr<MyScopedThing> MyWorkerObject::getScopedThing() {
return boost::shared_ptr<MyScopedThing>(new MyScopedThing(*this));
}
int main() {
boost::mutex m;
boost::mutex::scoped_lock l(m);
MyWorkerObject w;
const boost::shared_ptr<MyScopedThing>& mst = w.getScopedThing();
}
[generic@sentinel ~]$ g++ test.cpp -o test -lboost_thread -Wall
test.cpp: In function ‘int main()’:
test.cpp:33: warning: unused variable ‘mst’
[generic@sentinel ~]$ ./test
ab[generic@sentinel ~]$ g++ -v 2>&1 | grep version
gcc version 4.4.5 20110214 (Red Hat 4.4.5-6) (GCC)
推荐答案
请注意,自从写完其他答案后,问题已经发生了变化.
Note that the question has changed since the other answers were written.
g++ 在当前表单中没有发出警告的原因可能是因为 mst
是一个引用,并且构造和破坏一个引用没有副作用.确实,这里的引用延长了临时对象的生命周期,这对其构造函数和析构函数都有影响,但显然 g++ 并没有意识到这会有所不同.
Likely the reason g++ doesn't warn in the current form is because mst
is a reference, and constructing and destructing a reference has no side effects. It's true that here the reference is extending the lifetime of a temporary, which has effects in its constructor and destructor, but apparently g++ doesn't realise that makes a difference.
这篇关于scoped_lock 如何避免发出“未使用的变量"?警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:scoped_lock 如何避免发出“未使用的变量"?警告?
基础教程推荐
- C利用语言实现数据结构之队列 2022-11-22
- C++详细实现完整图书管理功能 2023-04-04
- C++使用easyX库实现三星环绕效果流程详解 2023-06-26
- C语言基础全局变量与局部变量教程详解 2022-12-31
- 一文带你了解C++中的字符替换方法 2023-07-20
- C++中的atoi 函数简介 2023-01-05
- C/C++编程中const的使用详解 2023-03-26
- C语言 structural body结构体详解用法 2022-12-06
- 如何C++使用模板特化功能 2023-03-05
- 详解c# Emit技术 2023-03-25