简体   繁体   中英

How to make Visual Studio 2010 warn about unused variables?

#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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM