I keep getting errors from the extinction person, but I'm using xcode, so I don't know which part is the problem ㅜ<
#include <stdio.h>
#include <iostream>
#include <cstring>
using namespace std;
class Person{
char* name;
char* addr;
public:
Person(const char *name, const char *addr){
this->name= new char[strlen(name)+1];
strcpy(this->name,name);
this->addr= new char[strlen(addr)+1];
strcpy(this->addr,addr);
cout<<"Create Person Object" ("<<name<<")"<<endl;
}
~Person(){
cout<<"Remove Person Object" ("<<name<<")"<<endl;
delete [] name;
delete [] addr;
}
void print() const{
"It's ""<<<name<<endl;" living in ""cout<<addr<<<<endl;""
}
//Create Move Creator
Person(Person&& human2) : name{human2.name}, addr{human2.addr} {
human2.name=nullptr;
human2.addr=nullptr;
cout<<"Person has moved~"<<endl;
}
void print(){
if((this->name == nullptr)&&(this->addr == nullptr)){
cout<<"This data is already missing"<<endl;
}
else{
cout<<"Name:"<<name<<"Address:"<<addr<<<endl;"
}
};
int main()
{
cout<<"Move C to D to execute constructor"<<endl;
Person C ("Kim Jjon-tteok" ("Seoul Metropolitan Government");
Person D = move(C);
C.print();
D.print();
cout<<endl;
}
<Result value>
Created a Person object (Kangshiru)
Move C to D Run the constructor
Person Create Object (Kim Chewy Rice Cake)
Person, I'm done moving
This data is already missing
Name: Kim Jjon Tteok Address: Seoul Metropolitan Government
Person Remove Object (Kim Chewy Rice Cake)
Person Remove object ((lldb) //where Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
error occurs.
I think there's a problem with nullptr. What is it?
c++ destructor
The reason for the error is that when the destructor is called, the name is output as cout even if the name is NULL.
You can delete it and change it to print it out only when it is not NULL as shown below.
~Person() {
if (name)
{
delete[] name;
cout << "Remove Person Object" ("<< name <<")" << endl;
}
if(addr)
delete[] addr;
}
562 Who developed the "avformat-59.dll" that comes with FFmpeg?
853 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
566 Understanding How to Configure Google API Key
563 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
589 GDB gets version error when attempting to debug with the Presense SDK (IDE)
© 2024 OneMinuteCode. All rights reserved.