alternative to strdup

aherlambang picture aherlambang · Mar 14, 2010 · Viewed 14.3k times · Source

I'm writing a C++ class for a book that contains a name:

class Book {
private:
    char* nm;
..........
............
..........
...........
};

I am not allowed to use std::string in this assignment. So here I am using strdup to copy the value of the parameter name into nm in the constructor:

Book::Book(const char *name, int thickness, int weight)
    : nm(NULL)
    , thck(thickness)
    , wght(weight)
{
    if (name)
        nm = strdup(name);
}

Is there an alternative of achieving the same result without using strdup, but using the keyword new instead?

Answer

dirkgently picture dirkgently · Mar 14, 2010

Strictly speaking: The string class is part of the Strings library. This is much easier to use, dynamic in nature and you have less worry when copying/assigning than C-style strings.

The other approach is to manually copy out:

class Book {
   public:
     Book(const char *name, ...) : nm(0), ... {
           if (!name) throw "invalid parameter";
           nm = new char [ strlen(name) + 1 ];
           strcpy(nm, name);
     }
     ~Book() {
           delete [] nm;
           // ...
     }
     Book(Book const& o) : nm(0), ... {
           if (!name) throw "invalid parameter";
           char *p = new char [ strlen(name) + 1 ];
           if (p) {
               strcpy(p, name);
               delete [] nm;
               nm = p; 
           }
     }
     Book& operator=(Book const& o) {
           if (this != &o) {
              char *p = new char [ strlen(name) + 1 ];
              if (p) {
               strcpy(p, name);
               delete [] nm;
               nm = p; 
              }
           }
           return *this;             
     }
 };

The problem with this approach is that you will have to manage the memory yourself and implement all the Big-three special member functions yourself (and ensure exception-safety as much as you can).