概述
从C转为C++,简单的逻辑如果没注意C++的类的特性性,就会将你的代码引入深渊。本文记录笔者在C++中使用结构体时遇到的错误。当前听同事感慨:C++最好不要用结构体。
采坑1
结构体中如果使用了C++中的类,比如string之类的。要特别小心不要在使用malloc、memcpy等操作。比如笔者犯的错误:
#include <iostream>
#include <string>
using namespace std;
struct test {
string a;
string b;
int c;
};
int main() {
struct test t1, *t2;
//初始赋值。
t1.a = "lean c++";
t1.b = "work hard";
t2 = (struct test *)malloc(sizeof(struct test));
memcpy(t2, &t1, sizeof(struct test));
cout << "t1->a:" << t1.a << endl;
cout << "t2->a:" << t2->a << endl;
//再次赋值。
t1.a = "my c";
t1.b = "keep learning";
cout << "t1->a:" << t1.a << endl;
cout << "t2->a:" << t2->a << endl;
return 0;
}
从上面可以看出,memcpy之后,t2对象的string a仍然引用到t1,并且值还不对。
采坑2
struct test {
string a;
string b;
int c;
};
void func1(struct test &t1);
面对上述左值引用的函数,需要定义结构体的构造函数跟析构函数。毕竟结构体也是一个特殊的类。