简体   繁体   English

复制构造函数和内存分配

[英]Copy Constructor and memory allocation

Why is the memory address of message.pmessage the same before and after the constructor is called? 为什么在调用构造函数前后,message.pmessage的内存地址相同? Shouldn't the memory address of message.pmessage be different if it was allocated with new? 如果message.pmessage的内存地址是用new分配的,它的地址应该不一样吗? I'm confused. 我糊涂了。

Overloaded Operator function 重载操作员功能

CMessage operator+(const CMessage& aMess) const
    {
      cout << "Add operator function called." << endl;
      size_t len = strlen(pmessage) + strlen(aMess.pmessage) + 1;
      CMessage message;

      //
      cout << &message.pmessage << endl;
      cout << message.pmessage << endl;
      message.pmessage = new char[len];
      message.test = new char[len];
      cout << &message.pmessage << endl;
      //

      strcpy_s(message.pmessage, len, pmessage);
      strcat_s(message.pmessage, len, aMess.pmessage);
      return message;
    }

Constructor 构造函数

CMessage(const char* text = "Default message")
{
  cout << "Constructor called." << endl;
  pmessage = new char[strlen(text) + 1];         // Allocate space for text
  strcpy_s(pmessage, strlen(text)+1, text);      // Copy text to new memory
}

在此处输入图片说明

you are printing the address of a pointer inside one object, of course it is always going to be the same. 您在一个对象内打印指针的地址,当然它总是会相同的。 To print out of the address that pointer is pointing to, you can try this 要打印出指针所指向的地址,可以尝试这样做

cout << static_cast<void*>(message.pmessage) << endl;

you need static_cast<void*> because you want to avoid printing the c string. 您需要static_cast<void*>因为您要避免打印c字符串。

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

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