I worked with C ++ in some midsized project, but I never made any serious C programs.
After reading this article, I began to wonder how I can use C ++ 11 without classes and exceptions. I once heard that the term clean C. Clean C should be C ++ - code that does not use C ++ functions that ANSI C does not have, such as classes or metaprogramming.
There are many resources on how to do things efficiently in C and how to do them in C ++. But it is surprisingly hard to find any resources on how to take the best of both worlds.
My question has two parts:
- Are there any good resources to use C ++ without namespaces, exceptions, and metaprogramming? Books, open source projects?
- Read this simple code snippet, which is my first attempt at processing data structures and char strings in a specified C ++ 11 subset. The first thing that comes to my mind is code redundancy. What do you do differently and why?
-
#include <cstring>
namespace addressbook {
namespace contact {
struct contact {
char* name;
char* email;
};
void initialize(addressbook::contact::contact* contact)
{
contact->name = nullptr;
contact->email = nullptr;
}
void deinitialize(addressbook::contact::contact* contact)
{
delete[] contact->name;
delete[] contact->email;
}
void set_name(addressbook::contact::contact* contact, char* name)
{
delete[] contact->name;
contact->name = new char [strlen(name) + 1];
std::strcpy(contact->name, name);
}
void set_email(addressbook::contact::contact* contact, char* email)
{
delete[] contact->email;
contact->email = new char [strlen(email) + 1];
std::strcpy(contact->email, email);
}
}
}
int main()
{
namespace c = addressbook::contact;
c::contact jimmy;
c::initialize(&jimmy);
c::set_name(&jimmy, const_cast<char*>("Jimmy Page"));
c::set_email(&jimmy, const_cast<char*>("jp@example.com"));
c::deinitialize(&jimmy);
return 0;
}
Please have mercy on me - I am new to programming.
Why not just C then?
Namespaces, new / deleted, standard library algorithms, accelerating libraries, cool features of C ++ 11 - to name a few.
Why new / delete when you don't have constructors / destructors?
Due to the type of security. mallocreturns*void
But the standard library throws exceptions! And boost too!
The fact that I do not use exceptions does not mean that I cannot handle exceptions from external libraries. It just means that I want to solve problems differently in my part of the system.