110 lines
2.5 KiB
C++
110 lines
2.5 KiB
C++
#include <iostream>
|
|
#include <memory>
|
|
|
|
void changeInt(int n);
|
|
void changeIntPointer(int* pN);
|
|
void changeIntReference(int& n);
|
|
|
|
void createInt(int* pI);
|
|
void createInt(int** ppI);
|
|
|
|
int main()
|
|
{
|
|
int i = 1;
|
|
int* pI = nullptr;
|
|
pI = &i;
|
|
*pI = 10;
|
|
std::cout << "i = " << i << std::endl;
|
|
pI = new int;
|
|
pI = new int(); // CAUTION - created a memory leak
|
|
pI = new int(10); // CAUTION - created a memory leak
|
|
delete pI;
|
|
pI = nullptr;
|
|
|
|
changeInt(i);
|
|
changeIntPointer(&i);
|
|
changeIntReference(i);
|
|
|
|
// const
|
|
// const int ci = 10; // integer is constant
|
|
// const int* pCi = new int(0); // pointer to a constant integer
|
|
// pCi = new int(0);
|
|
// *pCi = 0;
|
|
// int const * pic = new int(0); // pointer to a constant integer
|
|
// pic = new int(0);
|
|
// *pic = 0;
|
|
// const int const * pcic = new int(0); // pointer to a constant integer
|
|
// pcic = new int(0);
|
|
// *pcic = 0;
|
|
// int * const cpi = new int(0); // constant pointer to an integer
|
|
// cpi = new int(0);
|
|
// *cpi = 0;
|
|
// int const * const cpic = new int(0); // constant pointer to a constant integer
|
|
// cpic = new int(0);
|
|
// *cpic = 0;
|
|
// const int * const cpci = new int(0); // constant pointer to a constant integer
|
|
// cpci = new int(0);
|
|
// *cpci = 0;
|
|
// const int const * const cpcic = new int(0); // constant pointer to a constant integer
|
|
// cpcic = new int(0);
|
|
// *cpcic = 0;
|
|
|
|
createInt(pI);
|
|
createInt(&pI);
|
|
|
|
if (pI != nullptr) {
|
|
delete pI;
|
|
pI = nullptr;
|
|
}
|
|
|
|
std::unique_ptr<int> upI = std::make_unique<int>(0);
|
|
// std::unique_ptr<int> upI2 = upI; // don't work
|
|
std::unique_ptr<int> upI2 = std::make_unique<int>(*upI);
|
|
|
|
std::shared_ptr<int> spI = std::make_shared<int>(0);
|
|
std::shared_ptr<int> spI2 = spI;
|
|
spI.reset();
|
|
|
|
std::weak_ptr<int> wpI = spI2;
|
|
if (wpI.expired()) {
|
|
std::cout << "wpI is expired" << std::endl;
|
|
}
|
|
else {
|
|
std::cout << "wpI is not expired" << std::endl;
|
|
std::shared_ptr<int> spI3 = wpI.lock();
|
|
}
|
|
|
|
spI2.reset();
|
|
|
|
if (wpI.expired()) {
|
|
std::cout << "wpI is expired" << std::endl;
|
|
}
|
|
else {
|
|
std::cout << "wpI is not expired" << std::endl;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
void changeInt(int n) {
|
|
n *= 2;
|
|
}
|
|
|
|
void changeIntPointer(int* pN) {
|
|
if (pN == nullptr) return;
|
|
*pN *= 2;
|
|
}
|
|
|
|
void changeIntReference(int& n) {
|
|
n *= 2;
|
|
}
|
|
|
|
void createInt(int* pI) {
|
|
pI = new int(0);
|
|
}
|
|
|
|
void createInt(int** ppI) {
|
|
if (ppI == nullptr) return;
|
|
*ppI = new int(0);
|
|
}
|