From operator new, operator new[]
Class-specific overloads
Both single-object and array allocation functions may be defined as public static member functions of a class (versions (15-18)). If defined, these allocation functions are called by new-expressions to allocate memory for single objects and arrays of this class,
- So the new operator allocates memory for new instances of the class, not for the attributes of the class.
- If you need to allocate memory for attributes of the class do that e.g. in the constructor.
- Avoid the use of char* for strings. Rather use C++ Strings.
- Avoid pointers as much as possible. Have a look at smart pointers.
For the sake of completeness, if you must use char*, you can use strlen, new, strncpy and delete to do this. Do not use strcpy as this can cause an overflow.. (To get the below to compile in VS2015 you will need to add the _CRT_SECURE_NO_WARNINGS to the preprocessor definitions.)
int length = strlen(source) + 1;
char *destination = new char[length];
if (destination) {
strncpy(destination, source,length);
}
...
delete destination //do not forget to free the allocate memory
Here is the Student class.
- The 1st constructor takes a char* (for demonstration purposes only!)
- But better, the 2nd constructor uses
- no pointers,
- it uses C++ strings, and
- uses the constructors initializer list to setup the attributes.
- new operator (just delegates to the global new operator).
- delete operator (for completeness, delegates to global delete operator).
.
#include <iostream>
#include <string>
// class-specific allocation functions
class Student {
char *nameCharArray; //this only for demonstration
std::string name; //prefer string
int age;
public:
Student(char *name, int age) : age(age)
{
int length = strlen(name) + 1;
nameCharArray = new char[length];
if (this->nameCharArray) {
strncpy(this->nameCharArray, name, length);
}
this->name = std::string(nameCharArray);
}
Student(std::string &name, int age) : name(name), age(age) {}
~Student() {
std::cout << "Freeing name... " << std::endl;
delete nameCharArray;
}
std::string getName() const {
return name;
}
static void* operator new(std::size_t sz)
{
std::cout << "custom new for size " << sz << '\n';
return ::operator new(sz);
}
static void operator delete(void* ptr, std::size_t sz)
{
std::cout << "custom delete for size " << sz << '\n';
::operator delete(ptr);
}
};
This is how the code is used
int main() {
char name[] = "studentname";
Student* p1 = new Student(name, 12);
std::cout << p1->getName() << std::endl;
delete p1;
}