问题
I have a complicated least-squares fitting program, which I was recently debugging. I was debugging stuff by cout-ing them to the console, and to make it easier, I used
using namespace std;
and funnily, after weeks of coding, I wanted to remove this because debugging is done, and the surprise was that removing it causes the result to be wrong! I did a complete abstract check in g++ and icpc (intel compiler) where I remove and restore this directive, and when it's removed, the result it wrong...
I know it's a very broad question and not easy to hit the answer, but what would you do in this case? How would you debug such a dependence?
回答1:
This is why using-directives in the global namespace (or any other inappropriately wide scope) are a bad idea. It's not just a matter of style; it can change the meaning of the code in subtle ways. See this question for a thorough discussion of the issues.
Almost certainly, your code uses names from the standard library without qualification, and those names are also declared in the global namespace. Thus, removing using namespace std;
changes the meaning of those unqualified names, rather than just making the code fail to compile.
These might be names from your code; or perhaps they are C library functions. Many (particularly those in <cmath>
) are overloaded for various types, where the C library itself only declares a single function. It's unspecified whether none, some, or all of these are dumped into the global namespace as well as namespace std
.
For example, you might have a function call
float angle = whatever;
float sine = sin(angle);
With using namespace std;
, this will select the overloaded float std::sin(float)
that you've dumped into the global namespace. Without it, depending on what the implementation chooses to do with the global namespace, it might still call that; or it might call double sin(float)
from the C library; or it might fail to compile.
In the case of GCC, it seems that the C library function, but not the C++ overloads, are dumped into the global namespace, as I discovered while answering this question.
回答2:
Try objdump to get the difference of executable with & without "using namespace std;"
Use objdump -d [executable | objfile] to disassemble the ELF.
objdump executable-without-using-std -d > no-std;
objdump executable-with-std -d > with-std;
diff -urN no-std with-std;
If you see any difference function call instructions, then that should be the problematic one.
回答3:
Math functions usually cause these kind of issues. I was having problems with abs(), which switched to C-Style as soon as I removed the "using" directive.
来源:https://stackoverflow.com/questions/18740628/removing-using-namespace-std-causes-the-program-to-get-crap-results