带有堆栈变量和函数的 C++ 奇怪行为

C++ weird behaviour with stack variables and functions

提问人:psmith 提问时间:6/27/2018 最后编辑:Yakk - Adam Nevraumontpsmith 更新时间:6/27/2018 访问量:73

问:

我有一个带有 a 和 a 的类。Stringchar* bufferunsigned int length

字符串类有两个构造函数:

String(const char* str);
String(const String& other);

和析构函数

 ~String()

这将删除带有 的 char 数组。delete[] buffer;

这两个构造函数都创建一个新的缓冲区数组,并用 或 中的正确数据填充它。字符串缓冲区以 null 结尾。buffer = new char[size];const char* stringconst String& other

在我的主函数中,我有以下代码:

int main() {
    String a("Hello");
    a = a.Replace('l', 'p');
    printf("%s\n", a.char_ptr());
}

我希望它能打印到控制台。该函数采用两个字符,其中第一个字符的所有出现都由第二个字符替换。它返回一个全新的:HepporeplaceString

String String::Replace(const char& a, const char& b) {
    const char* buf = ...;
    // Do the replacement and store the result in buf

    String s(buf);
    delete[] buf;
    return s;
}

据我了解,编译器将返回局部变量的副本。因此,中的变量应该是完全合法的。但是控制台的输出看起来像 ,看起来像未初始化的内存。samain()String¦¦¦¦¦¦¦¦¦¦

更奇怪的是,当我将主要方法更改为:

int main() {
    String a("Hello");
    String b = a.Replace('l', 'p');
    printf("%s\n", b.char_ptr());
}

我看到了预期的输出。经过大量阅读,我无法找出解决方案,因为这个问题在 google/stackoverflow 搜索中真的很难描述。

C++ 变量 堆栈 法则

评论

0赞 6/27/2018
您需要一个赋值运算符
1赞 alter_igel 6/27/2018
a = a.Replace('1', 'p');是否定义了复制赋值运算符?
0赞 alter_igel 6/27/2018
看看三法则
0赞 psmith 6/27/2018
这是有道理的。oprator 的返回值应该是多少?我在想的只是一个普通的字符串:String String::opreator=(const String& other)
1赞 Barmar 6/27/2018
复制赋值应返回 ,而不是 。String&String

答:

0赞 Red.Wave 6/27/2018 #1

主要问题是违反了三巨头的规则。由于您有一个 None Trivial 析构函数,因此还必须定义一个 Copy 构造函数和一个赋值运算符。 在实现上述功能时,您可以考虑 copy-swap 习惯用法。 在存在非平凡的析构函数的情况下,未定义两者中的任何一个,都会导致资源(在此示例中的内存)泄漏。