gpt4 book ai didi

c++ - scoped_lock 如何避免发出 "unused variable"警告?

转载 作者:IT老高 更新时间:2023-10-28 22:30:16 25 4
gpt4 key购买 nike

boost::mutex::scoped_lock 是一个方便的 RAII 包装器,用于锁定互斥锁。我对其他事情使用了类似的技术:一个 RAII 包装器,它要求数据接口(interface)从/重新连接到串行设备。

不过,我想不通的是,为什么在下面的代码中只有我的对象 mst(其实例化和销毁 确实有副作用)会导致 g++ 发出“未使用的变量”警告错误,而 l 设法保持沉默。

你知道吗?你能告诉我吗?

[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)

最佳答案

请注意,在写完其他答案后,问题已经发生了变化。

g++ 在当前表单中没有发出警告的原因可能是因为 mst 是一个引用,并且构造和破坏一个引用没有副作用。确实,这里的引用延长了临时对象的生命周期,这对其构造函数和析构函数都有影响,但显然 g++ 并没有意识到这会有所不同。

关于c++ - scoped_lock 如何避免发出 "unused variable"警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com