anuragpatel.optnio
BAN USERIn C, strings are just char arrays which, by convention, end with a NUL byte. In terms of dynamic memory management, you can simply malloc the space for them (including the extra byte). Memory management when modifying strings is your responsibility:
char *s = strdup ("Hello");
char *s2 = malloc (strlen (s) + 6);
strcpy (s2, s);
strcat (s2, ", Pax");
free (s);
s = s2;
In C++, strings (std::string) are objects with all the associated automated memory management and control which makes them a lot safer and easier to use, especially for the novice. For dynamic allocation, use something like:
std::string s = "Hello";
s += ", Pax";
I know which I'd prefer to use, the latter. You can (if you need one) always construct a C string out of a std::string by using the c_str() method.
The correct answer is: don't. Garbage collection does not work well with C++.
Better to use RAII (which you can Google). Simply put, make sure that you have destructors to properly clean up all the resources you aquire.
std::mutex m;
void bad()
{
m.lock(); // acquire the mutex
f(); // if f() throws an exception, the mutex is never released
if(!everything_ok()) return; // early return, the mutex is never released
m.unlock(); // if bad() reaches this statement, the mutex is released
}
void good()
{
std::lock_guard<std::mutex> lk(m); // RAII class: mutex acquisition is initialization
f(); // if f() throws an exception, the mutex is released
if(!everything_ok()) return; // early return, the mutex is released
}
An approach that's both easy to implement and that gives the right answer is to create a static counter in Widget, increment the counter each time a Widget constructor is called, and decrement it whenever the Widget destructor is called. You also need a static member function how many to report how many Widgets currently exist. If Widget did nothing but track how many of its type exist, it would look more or less like this:
- anuragpatel.optnio July 25, 2017class Widget {
public:
Widget() { ++count; }
Widget(const Widget&) { ++count; }
~Widget() { --count; }
static size_t howMany()
{ return count; }
private:
static size_t count;
};
// obligatory definition of count. This
// goes in an implementation file
size_t Widget::count = 0;