简体   繁体   English

重载新运算符时,它不会为char指针分配内存

[英]when overloading new operator it doesnt allocate memory for char pointer

i ve overloaded new operator for the class which contains an integer variable and a character pointer. 我已经为包含一个整数变量和一个字符指针的类重载了新的运算符。 when overloaded the new operator allocates memory only for the integer as it first creates memory and then calls the constructor. 当重载时,新运算符仅为整数分配内存,因为它首先创建内存,然后调用构造函数。 could someone please tell me how to rectify this? 有人可以告诉我如何纠正这个问题吗?

//program for overloading new operator


//header files
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

class Student
{
   char *name;
   int age;
   public:
   Student(char *name,int age)
   {
     strcpy(name,this->name);
     this->age=age;
   }
  void disp()
  {
     cout<<"\n name is "<<name<<" age is "<<age<<endl;
  }
  void * operator new(size_t s)
  {
     cout<<" \n in new block and size is "<< s;
     void *ptr=malloc(s);
     if(!ptr) cout<<"\n memory full ";
     else return ptr;
  }
  void operator delete(void *ptr)
  {
     cout<<" \n in delete block ";
     free(ptr);
  }
};

main()
{
   clrscr();
   Student *ob=new Student("abc",15);
   ob->disp();
   delete ob;
   getch();
}

produces an output 产生输出

in new block and size is 4 name is age is 15 在新块中,大小为4名称是年龄是15

in delete block 在删除块中

From operator new, operator new[] 来自操作员new,操作员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)). 单对象和数组分配函数都可以定义为类的公共静态成员函数(版本(15-18))。 If defined, these allocation functions are called by new-expressions to allocate memory for single objects and arrays of this class, 如果已定义,则这些分配函数将由new-expressions调用, 以为此类的单个对象和数组分配内存

  • So the new operator allocates memory for new instances of the class, not for the attributes of the class. 因此,new运算符为类的新实例分配内存,而不是为类的属性分配内存。
  • If you need to allocate memory for attributes of the class do that eg in the constructor. 如果您需要为类的属性分配内存,请在构造函数中执行此操作。
  • Avoid the use of char* for strings. 避免对字符串使用char *。 Rather use C++ Strings . 而是使用C ++字符串
  • 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. 为了完整起见,如果必须使用char *,则可以使用strlen,new,strncpy和delete来执行此操作。 Do not use strcpy as this can cause an overflow. 不要使用strcpy,因为这会导致溢出。 . (To get the below to compile in VS2015 you will need to add the _CRT_SECURE_NO_WARNINGS to the preprocessor definitions.) (要使以下内容在VS2015中进行编译,您需要将_CRT_SECURE_NO_WARNINGS添加到预处理器定义中。)

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!) 第一个构造函数使用char *(仅用于演示目的!)
  • But better, the 2nd constructor uses 但更好的是,第二个构造函数使用
    • no pointers, 没有指针,
    • it uses C++ strings, and 它使用C ++字符串,并且
    • 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). delete运算符 (出于完整性考虑,委托给全局delete运算符)。

.

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM