Why and how can "using namespace" declarations confuse the compiler in C++? - c++

I have read about the "cout/cin is ambiguous" plenty of times by now, from many different kinds of sources, and I keep hearing:
"Use 'std::' as a prefix, since it elsewise might confuse your compiler"
Now, I do know that not using the scope operator can be a bad practise according to some, and that people who usually receives this sort of error is on an elementary stage in their programming. However, the sources says that I'm supposed to understand how this work with time, which unfortunately, I don't yet. I still receive the errors occasionally (since I, despite all the warnings, still use "using namespace" declarations), and I still don't get why it works in 99% or the cases, and not in the other.
I'm degugging my code in Visual Studio express (2012), and of course, all the required sources are included (which in this case is the iostream library), so there isn't any sort of permanent error; it actually tends to popup quite randomly (a couple of times for instance, I've changed a piece of code, making the error appear, then even after changing it back, the error persists)... Really, I don't see any logical explaination to why the error appears in random contexts - hence why I'm asking:
What is causing this error, exactly (what does it mean, and why and how does it confuse the processor)? Moreover, is it worth skipping these declarations because of that? Can't it be fixed somehow?
Thanks in beforehand!

This is how you can confuse it by doing using namespace ... religiously. Now suppose some library you are using has defined a function called foo. Let's assume it's boost or whatever. Maybe even your own namespace called "op". You have a function called foo. My namespace may have the same function signature as yours. If you import both namespaces, how will the compiler know which to call? See below for example.
#include <cstdio>
namespace me
{
void foo()
{
printf("%s", "Calling me::foo\n");
}
}
namespace op
{
void foo()
{
printf("%s", "Calling op::foo\n");
}
}
using namespace me;
using namespace op;
int main()
{
foo(); //abiguous call.. Which foo is it going to use? op::foo? Or me::foo?
//now remove the using namespace me and using namespace op.. then try the below:
me::foo();
op::foo();
//The compiler now knows which foo you're trying to call and calls the correct one.
}

Related

C++ indentifier "read" conflicts?

Recently I'm working on my toy final c++ project, which will read content from a file at the begining and then process it.
Here's the simplified code.
#include <iostream>
#include <fstream>
//using namespace std;
struct command{
int a;
};
command read[1];
int main() {
std::ifstream fin;
fin.open("123.txt");
if (!fin){
std::cout << "failed" << std::endl;
return 0;
}
char c;
fin >> c;
std::cout << c;
return 0;
}
It works fine with Visual Studio 2019. However, when I'm trying to use devc++ 5.11 TDM-GCC 4.9.2, a strange bug happens. I get a segmentation fault on line fin>>c;, with return code 3221225477.
With great effort, the easiest way to make this code works is changing the identifier read to names like reading or whatever. Besides, moving the line command read[1]; into main function also helps.
My questions are:
Is it a behavior related to the compiler? MSVC is fine but GCC 4.9.2 is a little bit old or ...?
Does the identifier read conflict with something in my code? Why does it not a compile error but a segmentation fault?
Why does moving the declaration of read into main function help?
Update:Thanks for tips and I removed using namespace std. I think it has something to do with ifstream, because just std::cout<<"hello world"; works.
-Wall -Wextra provides no warnings.
GCC compiler is stricter than other compiler.
According to tadman's describe, we can guess there's read symbol in namespace std.
So you put it out of main,it's a conflict, you put in the main, it become a local symbol.
There is very likely a collision happening between your read and another in the global namespace. Not all compilers handle this situation the same way, but you can always avoid it if you are careful.
Visual Studio's Intellisense (or whatever alternative you prefer) can help you identify what symbol your read is colliding with. To do that, scope or comment out your code, then start typing "read". If there's another read in your scope, you'll likely see it and be able to get information about it.
This is one of the reasons I don't like using namespace std;. It pollutes your global namespace with a bunch of stuff and increases your chance of collision with a standard library identifier.

Netbeans 8.2 code assistance issue with unique_ptr (not shared_ptr)

Using Netbeans 8.2 on Linux and GCC 8.1, unique_ptr::operator->() gives an erroneous warning
Unable to resolve template based identifier {var} and more importantly will not autocomplete member names.
Code compiles and runs just fine, and amazingly, the autocomplete still works with no warnings if a shared_ptr is used instead. I have no idea how that is possible. Here is a problematic example, for reference
#include <iostream>
#include <memory>
struct C { int a;};
int main () {
std::unique_ptr<C> foo (new C);
std::shared_ptr<C> bar (new C);
foo->a = 10; //Displays warning, does not auto-complete the members of C
bar->a = 20; //No warning, auto-completes members of C
return 0;
}
I've tried the following to resolve this issue with no luck:
Code Assistance > Reparse Project
Code Assistance > Clean C/C++ cache and restart IDE
Manually deleting cache in ~/.cache/netbeans/8.2
Looking through View > IDE Log for anything that may help
Setting both the C and C++ compilers to C11 and C++11 in project properties
Changing the pre-processing macro __cplusplus to both 201103L and 201402L
Creating a new Netbeans project and trying the above
A large variety of permutations of the above options in different orders
Again, everything compiles and runs just fine, it's just Code Assistance that is giving me an issue. I've run out of things that I've found in other stack overflow answers. My intuition tells me that shared_ptr working and unique_ptr not working is helpful, but I don't know enough about C++ to utilize that information. Please help me, I need to get back to work...
Edit 1
This stack overflow question, although referencing Clang and the libc++ implementation, suggests that it may be an implementation issue within GCC 8.1's libstdc++ unique_ptr.
TLDR Method 1
Add a using pointer = {structName}* directive in your structure fixes code assistance, and will compile and run as intended, like so:
struct C { using pointer = C*; int a;};
TLDR Method 2
The answer referenced in my edit does in fact work for libstdc++ as well. Simply changing the return type of unique_ptr::operator->() from pointer to element_type* will fix code assistance, compile and run as expected (the same thing can be done to unique_ptr::get()). However, changing things in implementations of the standard library worries me greatly.
More Information
As someone who is relatively new to c++ and barely understands the power of template specializations, reading through unique_ptr.h was scary, but here is what I think is messing up Netbeans:
Calling unique_ptr::operator->() calls unique_ptr::get()
unique_ptr::get() calls the private implementation's (__unique_ptr_impl) pointer function __unique_ptr_impl::_M_ptr(). All these calls return the __unique_ptr_impl::pointer type.
Within the private implementation, the type pointer is defined within an even more private implementation _Ptr. The struct _Ptr has two template definitions, one that returns a raw pointer to the initial template variable of unique_ptr, and the second that seems to strip any reference off this template variable, and then find it's type named pointer. I think that this is where Netbeans messes up.
So my understanding is when you call unique_ptr<elementType, deleterType>::operator->(), it goes to __unique_ptr_impl<elementType, deleterType>, where the internal pointer type is found by stripping elementType of any references and then getting the type named dereferenced(elementType)::pointer. So by including the directive using pointer =, Netbeans gets what it wants in finding the dereferenced(elementType)::pointer type.
Including the using directive is entirely superficial, evidenced by the fact that things will compile without it, and by the following example
#include <memory>
#include <iostream>
struct A{
using pointer = A*;
double memA;
A() : memA(1) {}
};
struct B {
using pointer = A*;
double memB;
B() : memB(2) {}
};
int main() {
unique_ptr<A> pa(new A);
unique_ptr<B> pb(new B);
std::cout << pa->memA << std::endl;
std::cout << pb->memB << std::endl;
};
outputs
1
2
As it should, even though in struct B contains using pointer = A*. Netbeans actually tries to autocomplete B-> to B->memA, further evidence that Netbeans is using the logic proposed above.
This solution is contrived as all hell but at least it works (in the wildly specific context that I've used it) without making changes to implementations of stl. Who knows, I'm still confused about the convoluted typing system within unique_ptr.

Is it still considered bad practice when I use “using std::cout;” and so on? [duplicate]

This question already has an answer here:
C++ - Best Practice: `using std::cout` vs `std::cout` [closed]
(1 answer)
Closed 1 year ago.
It's obvious why using
using namespace std;
is considered bad practice. As I'm fairly new to C++ (about 8 months now) I wondered if it is still considered bad practice when I use
using std::cout;
using std::cin;
using std::endl;
and so on to only include what I need instead of including the whole namespace. My old teacher always told us to not use that as well but my new teacher told us it's just fine to use the using-Declaration compared to including the whole namespace.
What do you use and would you consider it a bad practice or not?
I hope this question is not a duplicate but I did not find another question like this, just questions about why it's considered to be bad practice to use using namespace std;, but like mentioned above I already know that.
I didn't like my original answer, too wordy, so here's a better rewrite.
Here's a good answer on why using namespace is bad.
With that answer in mind, if the library Foo has function kept and Bar has the function lept. With 2 using-directives, you can use both kept and lept without the scope. If Foo decides to update, and adds a function lept, then your compiler of choice will either give an error, or have undefined behavior*. If you use using Foo::kept and using Bar::lept, then an update on Foo that adds lept will not cause any error, and you can use Foo::lept to call that new function. It is also considered proper form with using-directives to not use them globally. Rather, for each function that you want to use a using-directive, redefine it. It is not bad practice to use using std::cout and the like, and in some instances, allows for quick library changes. For instance, I am using a JSON parsing library. To test them all, I added a using json = LIBRARY::json line to the start of my program, allowing me to quickly change out libraries if I did not like the one I had.
*For example, if Bar has lept defined as double lept(double, double), but Foo has lept defined as int lept(int, int), then a call to lept with 2 int inputs would call to Foo::lept or give an error on compile time. This means you won't know you have a massive error in your program until you test it.

Raise compile error if braces not closed at end of file (C++)

Is there a way to raise a warning or error if the C++ compiler comes to the end of file without all braces being closed? We never use headers which spill a scope into another file and would like to receive compiler warnings if it happens by accident. Compiler MSVC 2010, but others might be of interest too.
// Utilities.hpp
namespace example
{
class Utilities
{
}
//<EOF> -> should warn or error
Edit: I am willing to put a marker/pragma/Macro at the end of each file, where I know the brace level should be 0.
A reasonable method is
#define AT_GLOBAL_SCOPE namespace { }
because that can only appear at global or namespace scope. So it unfortunately won't catch that missing } from another namespace, but it will catch the class-case, as well as missing parentheses and semicolons.
In principle, this isn't known by the compiler proper - the preprocessor is sufficiently separate from the compiler proper that different files are "not known", it's just one long stream of source-code as far as the compiler is concerned.
One of the problems here is that the "understanding of the source code" is different at different levels. The preprocessor which inserts the #include ... into the source stream doesn't really know anything about { and } in other ways than "they are not alphanumeric" [which affects how macros and such are handled]. And consider that you could have [even if it's perhaps a bad idea]:
#define START {
#define END }
start
...
...
end
(The C preprocessor CAN be used for other things than C-code, so it's not "meant" to understand the language it is compiling)
I guess you could write a small tool that parses code and just counts up for { and down for }, and check for equality [you have to care for quotes and comments, but everything else should be counted]. But of course, the compiler will eventually tell you in some way, so I'm not sure that's much use. That assumes that there are no uneven sets of braces in macros.

Using namespace std vs other alternatives [duplicate]

This question already has answers here:
Why is "using namespace std;" considered bad practice?
(41 answers)
Closed 8 years ago.
using namespace std;
So far in my computer science courses, this is all we have been told to do. Not only that, but it's all that we have been allowed to do, otherwise we get penalized on our code. I understand, through looking at code posted online, that you can use ::std or std:: to accomplish the same thing.
My question is generall why? Obviously for the sake of learners and simplicity using the global declaration is simpler, but what are the draw backs? Is it more realistic to expect ::std in a real world application? And I guess to add on to this, what is the logic/concept behind the using declaration? None of this has been explained during my courses, and I'd like to get a better grasp on it.
As a general question: if I haven't been taught this content, vectors, templates, classes, or error handling does it seem like I'm missing a lot of essential C++ functionality?
Thanks in advance!
This is really one of those things that you can discuss over beer for hours and hours, and still not have an answer everyone is happy with.
If you are nearly always using std:: functionality, then adding using namespace std; at the beginning of the file is not that bad an idea. On the other hand, if you are using things from more than one namespace (e.g. writing a compiler using llvm:: and also using std::, it may get confusing as to which parts are part of llvm and which parts are std:: - so in my compilter project, I don't have a single file with using namespace ...; - instead I write out llvm:: and std:: as needed. There are several functions (unwisely, perhaps) called Type(), and some places use something->Type()->Type() to get the type-thing that I need... Yes, it confuses even me a little at times...
I also have many things that look like Constants::ConstDecl and Token::RightParen, so that I can quickly see "what is what". All of these COULD be made shorter and "simpler", but I prefer to see where things belong most of the time.
Being more verbose helps making it easier to see where things belong - but it makes for more typing and more reading, so it is a balance.
I'd say that generally, you do not declare the use of std globally. I guess if you're making a simple application, that would suffice. However, when you work in a large organization you often times have different namespaces that are used, and those might have overlapping objects. If you have a function in std, and in a namespace that you created, and then call "using namespace std" AND "using namespace yournamespace", you'll get unwanted results when calling that function. When you prefix every call with the namespace, it keeps it clearer and doesn't give issues with overlap.
general why?
Naming things is one of the more difficult aspects of software development. Beginners simply have little idea of how their name choices might generate ambiguities later on.
In particular, our software jargon often has preferred terms for certain issues. These preferences can cause unrelated class instances to be developed with the same (or similar) symbol with similar meanings.
Some of my often used symbols include init(), exec(), load(), store(), and I use timeStampGet() lots of places. I also use open(), close(), send()/recv() or write()/read().
So, I could rename init() in each of the 3 name spaces, and 5 objects into which I have added it, but it is much simpler to specify which one I want.
I find exec() in 2 name spaces and 12 objects. And there are 3 different timeStampGet() methods that I use. Whether namespaces or functions or class methods, these symbols make sense to me.
Furthermore, I find the 5 char "std::" namespace-as-prefix completely natural, and much preferable to the global "using namespace std". I suppose this comes with practice.
One more item - any where a larger name space or class name becomes tiresome, I sometimes add a typedef short name ... here are some examples from production code:
typedef ALARM_HISTORY ALM_HST;
typedef MONITOR_ITEM MI
typedef BACKUP_CONTROL BC;
On one team, we agreed to use well defined 'full' names, which, occasionally, became tiresome because of the length. Later in the project, we agreed that typedefs (for short class or namespace names) could be used when they were simple and added no confusion.
Personally I hate 'using' declarations. To me they make code unreadable and you break namespaces. I've spent 20 years as a maintenance programmer and I hate anything that make the code harder to read - in my mind using is as useless as throw specifications.
What is more readable 6months - a year - 10 years down the line
UDP::Socket sock
sock.send(data)
TCP::Socket sock2
sock2.send(data)
vs
using UDP;
using TCP;
sock.send(data)
sock2.end(data)
I also don't like namespace aliases
using namespace po = boost::program_options;
Now you are making the next programmer work harder with an extra level of indirection looking up what po is compared to boost::program_options. Same goes for those horrible typedef of
typedef long QUADWORD;
What size is a quadword - how long is a long 4 bytes? 8 bytes maybe 17 bytes on my OS
My last take is if you cannot type then don't be a programmer - a saved keystroke != good maintainable code