简体   繁体   English

复制构造函数中的std :: string行为

[英]Std::string behavior in copy constructor

The assignment operator of std::string in copy constructor does not perform a deep copy. 复制构造函数中std :: string的赋值运算符不会执行深层复制。

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; 程序在cout行<<“” Geekname is:\\ n“ << geekname;崩溃。 in obj2 printname call. 在obj2 printname调用中。 char* deep copy is working good. char *深层复制效果很好。

The problem is: 问题是:

    Geeks *obj2=obj1;
    delete obj1;

This doesn't invoke the Geeks copy constructor at all. 这根本不会调用Geeks复制构造函数。 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. 如果按值保存对象(例如Geeks obj1("Abhi"); ),一切都会好起来,并且std::string将执行适当的深层复制。

Also, beware: 另外,请注意:

A) Your constructor doesn't initialize cs . A)您的构造函数没有初始化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. 初始化为nullptr并进行测试要好得多。

B) You need an assignment operator (or you need to delete it). B)您需要一个赋值运算符(或需要将其delete )。

C) (As noted in the comments) You need new char[10] to create an array. C)(如注释中所述)您需要new char[10]创建一个数组。 new char(10) will create a single char with value 10. new char(10)将创建一个值为10的单个char。

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);

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

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