注:不保证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>();
失败时返回空指针 判断下就好