c++ - 复制构造函数为动态分配做了什么

标签 c++

<分区>

我很好奇为什么拷贝构造函数对于我自己定义类的动态分配如此重要。

我正在实现具有动态分配的低级 c 字符串类,这是我的类的快速 View

class String
{
private:
    char * buf;
    bool inBounds( int i )
    {
        return i >= 0 && i < strlen(buf);
    }
    static int strlen(const char *src)
    {
        int count = 0;
        while (*(src+count))
            ++count;
        return count;
    }
    static char *strcpy(char *dest, const char *src)
    {
        char *p = dest;
        while( (*p++ = *src++));
        return dest;
    }
    static char* strdup(const char *src)
    {
        char * res = new_char_array(strlen(src)+1);
        strcpy(res,src);
        return res;
    }
    static char * new_char_array(int n_bytes)
    {
        return new char[n_bytes];
    }
    static void delete_char_array( char* p)
    {
        delete[] p;
    }

public:
    /// Both constructors should construct
    /// this String from the parameter s
    String( const char * s = "")
    {
        buf = strdup(s);
    }
    String( String & s)
    {
        buf = strdup(s.buf);
    }
    void reverse()
    {
    }
    void print( ostream & out )
    {
        out << buf;
    }
    ~String()
    {
        delete_char_array(buf);
    }
};
ostream & operator << ( ostream & out, String str )
{
    str.print(out);
    return out;
}

我知道 strdup() 函数的部分并不正确,但我只是在做一些测试。

我的问题是如果我没有复制构造函数而我的 main() 是

int main()
{
    String b("abc");
    String a(b);
    cout << b << endl;
    return 0;
}

编译器会告诉我double free or corruption (fasttop) 我找到了关于这个问题的一些答案并查看了三大规则。

如果我有复制构造函数,你们能告诉我为什么我的代码没有任何错误吗?双重释放或损坏(fasttop)的错误是什么意思?

最佳答案

如果你没有定义拷贝构造函数,编译器会为你插入一个。这个默认的复制构造函数将简单地复制所有数据成员,因此 String 的两个实例将指向相同的内存区域。 buf 变量将在每个实例中保存相同的值。

因此,当实例超出范围并被销毁时,它们都会尝试释放相同的内存区域,并导致错误。

关于c++ - 复制构造函数为动态分配做了什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35166218/

相关文章:

c++ - 我可以通过 c 或 c++ 中的另一个 UDS 连接传递 UDS 文件描述符吗

C++ 程序编译器错误 : No Matching Function

c++ - 何时使用 =default 与 =delete

c++ - Apple C++ LLVM 编译器 4.x 和 UNICODE : when needed? UNICODE 是默认编译器字符集吗?使您的代码同时编译 ANSI 和 UNICODE 版本

c++ - boost 日志到文件不起作用

C++ 该代码 fstream 有什么问题

c++ - 这段代码是否依赖于函数调用顺序未定义的行为?

c++ - 奇怪的多重定义错误

c++ - 将菜单资源添加到对话框

c++ - map/unordered_map 插入期间内存分配失败