问题
#include <string>
using namespace std;
int main()
{
string s; // no warning
int i; // warning C4101
return 0;
}
- Why does Visual Studio warn me about the unused variable
i
but not abouts
in the example? - I assume that the compiler is not sure about side effects of the string constructor. Is this the reason for not showing a warning?
- 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