scoped_lock如何避免发出"未使用的变量"警告?

Lig*_*ica 15 c++ boost g++ compiler-warnings

boost::mutex::scoped_lock是一个方便的RAII包装锁定互斥锁.我在其他方面使用了类似的技术:RAII包装器要求数据接口与串行设备分离/重新连接.

但是,我无法弄清楚的是,为什么在下面的代码中只有我的对象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)
Run Code Online (Sandbox Code Playgroud)

yme*_*ett 6

请注意,自编写其他答案以来,问题已更改.

可能g ++没有在当前形式中警告的原因是因为它mst是一个引用,构造和破坏引用没有副作用.确实,这里的引用是延长临时的生命周期,它在构造函数和析构函数中有效,但显然g ++没有意识到这会产生影响.

  • +1:当编译器处理临时绑定到const引用时,它会注入一个未命名的局部变量,然后将其与引用绑定.当它执行静态分析时,它可能会看到类似于`type __internal的代码; 输入const&r = __internal;`并找到引用*unused* (2认同)