提问人:psmith 提问时间:6/27/2018 最后编辑:Yakk - Adam Nevraumontpsmith 更新时间:6/27/2018 访问量:73
带有堆栈变量和函数的 C++ 奇怪行为
C++ weird behaviour with stack variables and functions
问:
我有一个带有 a 和 a 的类。String
char* buffer
unsigned int length
字符串类有两个构造函数:
String(const char* str);
String(const String& other);
和析构函数
~String()
这将删除带有 的 char 数组。delete[] buffer;
这两个构造函数都创建一个新的缓冲区数组,并用 或 中的正确数据填充它。字符串缓冲区以 null 结尾。buffer = new char[size];
const char* string
const String& other
在我的主函数中,我有以下代码:
int main() {
String a("Hello");
a = a.Replace('l', 'p');
printf("%s\n", a.char_ptr());
}
我希望它能打印到控制台。该函数采用两个字符,其中第一个字符的所有出现都由第二个字符替换。它返回一个全新的:Heppo
replace
String
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;
}
据我了解,编译器将返回局部变量的副本。因此,中的变量应该是完全合法的。但是控制台的输出看起来像 ,看起来像未初始化的内存。s
a
main()
String
¦¦¦¦¦¦¦¦¦¦
更奇怪的是,当我将主要方法更改为:
int main() {
String a("Hello");
String b = a.Replace('l', 'p');
printf("%s\n", b.char_ptr());
}
我看到了预期的输出。经过大量阅读,我无法找出解决方案,因为这个问题在 google/stackoverflow 搜索中真的很难描述。
答:
主要问题是违反了三巨头的规则。由于您有一个 None Trivial 析构函数,因此还必须定义一个 Copy 构造函数和一个赋值运算符。 在实现上述功能时,您可以考虑 copy-swap 习惯用法。 在存在非平凡的析构函数的情况下,未定义两者中的任何一个,都会导致资源(在此示例中的内存)泄漏。
上一个:复制构造函数中的递归调用
下一个:具有结构的类中的析构函数问题
评论
a = a.Replace('1', 'p');
是否定义了复制赋值运算符?String String::opreator=(const String& other)
String&
String