c++指针相关知识

注:不保证100%正确

1.const对指针的修饰

当指针被const修饰时,分两种情况

1.普通指针

    1.1 当const在类名前,修饰的是指针指向的内容

    1.2 当const在类名后时,修饰的是指针地址本身

    1.3 当const既在类名前又在类名后,既修饰指针地址本身,又修饰指针指向内容。

2.智能指针

    无论const位于何处,都是修饰指针地址本身

class MyClass
{
public:
    MyClass() {};
    ~MyClass() {};
    MyClass(int number) {
        theNumber = number;
    };
    MyClass(int number,std::string info) {
        theNumber = number;
        text = info;
    };
    int theNumber = 0;
    std::string text = "";

    void setNumber(int number) {
        this->theNumber = number;
    }
    void PrintInfo(std::string text = "") {
        std::cout << "Is My class , " << text << std::endl;
    }
};

普通指针

    //普通指针
    MyClass* myPtrBase = new MyClass();


    const MyClass* myptr1 = new MyClass();  //const修饰指向的内容
    myptr1 = myPtrBase; //编译通过
    //myptr1->theNumber = 100;  编译不过

    MyClass* const myPtr2 = new MyClass();  //const修饰指针本身
    myPtr2->theNumber = 200; //编译通过
    //myPtr2 = myPtrBase; 编译不过
    
    const MyClass* const myPtr3 = new MyClass();  //const既修饰本身 也修饰指向内容
    // myPtr3 = myPtrBase; //编译不过
    // myPtr3->theNumber = 200; //编译不过

智能指针

    std::shared_ptr<MyClass> sharPtrBase = std::make_shared<MyClass>();


    const std::shared_ptr<MyClass> sharPtr1 = std::make_shared<MyClass>();
    sharPtr1->theNumber = 100;
    sharPtr1->setNumber(200);
    //sharPtr1 = sharPtrBase; //编译错误 const修饰指针本身

    std::shared_ptr<MyClass> const sharPtr2 = std::make_shared<MyClass>();
    sharPtr2->theNumber = 200;
    // sharPtr2 = sharPtrBase; //错误 const也是修饰指针本身

    const std::shared_ptr<MyClass> const sharPtr3 = std::make_shared<MyClass>();
    sharPtr3->theNumber = 200;
    // sharPtr2 = sharPtrBase; //错误 const也是修饰指针本身

2.内存分配

char* dest = (char*)malloc(iLen + 1);

当malloc失败时,返回的是空指针。因此每次malloc后都要判断是否为空。

if(dest == NULL) {return;}

myclass * ptr = new myclass();

当new失败时,抛出的是异常,会崩溃。

因此new指针时最好改成  myclass * ptr = new (std::nothrow) myclass();

当new加上了 (std::nothrow),那么分配内存失败就不会再抛出异常,而是返回空指针,因此分配后也要判断下。

if(ptr == nullptr) {return;}

std::share_ptr<myclass> ptr = std::make_share<myclass>(); 

失败时返回空指针 判断下就好

3.一些题目

c++ char指针相关的字符处理_京日暮里的博客-优快云博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值