How to make Visual Studio 2010 warn about unused variables?

ⅰ亾dé卋堺 提交于 2019-12-23 09:34:25

问题


#include <string>

using namespace std;

int main()
{
    string s; // no warning
    int i;    // warning C4101

    return 0;
}
  1. Why does Visual Studio warn me about the unused variable i but not about s in the example?
  2. I assume that the compiler is not sure about side effects of the string constructor. Is this the reason for not showing a warning?
  3. Can I somehow enable warnings about unused string variables?

My warning level is set to 4.


回答1:


I hypothesize that compilers only warn about unused variables for trivially constructible/destructible types.

template<typename>
struct Empty
{

};

template<typename T>
struct Trivial : Empty<T>
{
    int* p;
    int i;
};

template<typename>
struct NonTrivial
{
    NonTrivial() {}
};

template<typename>
struct TrivialE
{
    TrivialE& operator=(const TrivialE&) {}
};

struct NonTrivial2
{
    NonTrivial2() {}
};

struct NonTrivialD
{
    ~NonTrivialD() {}
};

int main()
{
    Empty<int> e;      // warning
    Trivial<int> t;    // warning
    NonTrivial<int> n; // OK
    TrivialE<int> te;  // warning
    NonTrivial2 n2;    // OK
    NonTrivialD nd;    // OK
}

Comparison of compilers' treatment

As can be observed, they are consistent.

Since std::string cannot possibly be trivially destructible, the compilers won't warn about it.

So to answer your question: you can't.




回答2:


There is no warning because actually there is no unused variable s. s is an instance of the string class and this class has a constructor which is called upon the declaration string s;, therefore s is used by it's constructor.




回答3:


std::string is not a primitive type, while int is. Non-primitive types have constructors and destructors, which may perform some useful functions: memory management, output to screen and so on, therefore declaration of a non-primitive type does not necessarily mean that the variable is not used. string does not do anything like this, of course, but probably they supress warnings for known types also having in mind that you may come up with the idea of redifining the string behavior (and you can do this by editing some header files since string is based on a template class).



来源:https://stackoverflow.com/questions/44646068/how-to-make-visual-studio-2010-warn-about-unused-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!