C++ 之结构体注意事项

概述

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

面对上述左值引用的函数,需要定义结构体的构造函数跟析构函数。毕竟结构体也是一个特殊的类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值