简体   繁体   中英

Std::string behavior in copy constructor

The assignment operator of std::string in copy constructor does not perform a deep copy.

I have run the code in different compilers but not of much use.

#include <iostream> 
#include <cstring>
using namespace std; 
class Geeks 
{
    public: 
    string geekname;
    char* cs;
    Geeks(string g)
    {
        geekname=g;
    }
    Geeks(const Geeks &obj)
    {
        this->geekname= (obj.geekname);
        this->cs=new char(strlen(obj.cs));
        strcpy(this->cs,obj.cs);
    }
     void printname() 
    { 
    cout << "Geekname is: \n" << geekname; 
       cout << "Geek informal name is: \n" << cs; 
    } 
}; 


int main() { 
    Geeks *obj1=new Geeks("Abhi"); 
    obj1->cs=new char(10);
    strcpy(obj1->cs,"tejgadu");
    obj1->printname(); 
    Geeks *obj2=obj1;
    delete obj1;
    obj2->printname(); 

    return 0; 
} 

The program is crashing at line cout << "Geekname is: \\n" << geekname; in obj2 printname call. char* deep copy is working good.

The problem is:

    Geeks *obj2=obj1;
    delete obj1;

This doesn't invoke the Geeks copy constructor at all. It just copies the pointer to the (one) object. You then delete that object, and (unsurprisingly) can't do anything with it.

Pointers to objects are not the same as objects. If you hold the objects by value, (eg Geeks obj1("Abhi"); ) all will be well and std::string will do a proper deep copy.

Also, beware:

A) Your constructor doesn't initialize cs . It will be a random value if you don't set it by hand. Much better to initialize to nullptr and test for that.

B) You need an assignment operator (or you need to delete it).

C) (As noted in the comments) You need new char[10] to create an array. new char(10) will create a single char with value 10.

You simply never create a second object, you only copy a pointer to the first object! As you delete your first object and call a method on it, your program typically will crash or do something else ( undefined behavior )

You can change it by using:

Geeks *obj2=new Geeks(*obj1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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