103 lines
2.3 KiB
C++
103 lines
2.3 KiB
C++
#include <iostream>
|
|
#include <memory>
|
|
#include <ostream>
|
|
|
|
void changeInt(int n);
|
|
|
|
void changeIntPointer(int *pN);
|
|
|
|
void changeIntReference(int &n);
|
|
|
|
void createInt(int *pN);
|
|
|
|
void createInt(int **ppN);
|
|
|
|
int main() {
|
|
int i = 5;
|
|
int *pI = nullptr;
|
|
pI = &i;
|
|
*pI = 10;
|
|
pI = new int;
|
|
pI = new int(); // CAUTION - memory leak created
|
|
pI = new int(10); // CAUTION - memory leak created
|
|
delete pI;
|
|
pI = nullptr;
|
|
|
|
int &rI = i; // reference
|
|
|
|
changeInt(i);
|
|
changeIntPointer(&i);
|
|
changeIntReference(i);
|
|
|
|
createInt(pI);
|
|
createInt(&pI);
|
|
|
|
// const
|
|
// const int ci = 5; // constant integer
|
|
// const int* cpi = new int(0); // pointer to a constant integer
|
|
// cpi = new int(10);
|
|
// *cpi = 10;
|
|
// int const * pci = new int(0); // pointer to a constant integer
|
|
// pci = new int(10);
|
|
// *pci = 10;
|
|
// int * const pic = new int(0); // constant pointer to an integer
|
|
// pic = new int(10);
|
|
// *pic = 10;
|
|
// const int * const cpic = new int(0); // constant pointer to a constant integer
|
|
// cpic = new int(10);
|
|
// *cpic = 10;
|
|
// int const * const pcic = new int(0); // constant pointer to a constant integer
|
|
// pcic = new int(10);
|
|
// *pcic = 10;
|
|
// const int const * cpci = new int(0);
|
|
// const int const * const cpcic = new int(0);
|
|
|
|
std::unique_ptr<int> upi = std::make_unique<int>(10);
|
|
// std::unique_ptr<int> upi2 = upi; // don't work
|
|
std::unique_ptr<int> upi3 = std::make_unique<int>(*upi);
|
|
|
|
std::shared_ptr<int> spi = std::make_shared<int>(10);
|
|
std::shared_ptr<int> spi2 = spi;
|
|
spi.reset();
|
|
|
|
std::weak_ptr<int> wpi = spi2;
|
|
if (wpi.expired()) {
|
|
std::cout << "expired" << std::endl;
|
|
} else {
|
|
std::cout << "not expired" << std::endl;
|
|
std::shared_ptr<int> spi3 = wpi.lock();
|
|
}
|
|
|
|
spi2.reset();
|
|
|
|
if (wpi.expired()) {
|
|
std::cout << "expired" << std::endl;
|
|
} else {
|
|
std::cout << "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 *pN) {
|
|
pN = new int(10);
|
|
}
|
|
|
|
void createInt(int **ppN) {
|
|
if (ppN == nullptr) return;
|
|
*ppN = new int(10);
|
|
}
|