-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuniquePtr.cpp
More file actions
executable file
·80 lines (80 loc) · 2.42 KB
/
uniquePtr.cpp
File metadata and controls
executable file
·80 lines (80 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* ATIVIDADE 3 - SI300/A
* DEMONSTRAÇÃO DE USO DO PONTEIRO INTELIGENTE UNIQUE_PTR
* UNICAMP - FACULDADE DE TECNOLOGIA
* 2016
*/
#include <cstdlib>
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Inteiros{
public:
void setNumero();
void getNumero();
~Inteiros();
private:
vector <unique_ptr<int>> inteiros;
};
Inteiros::~Inteiros(){
cout << endl;
cout << "Limpando lista" << endl;
/*
* COM USO DO PONTEIRO INTELIGENTE UNIQUE_PTR, TORNA-SE
* DESNECESSÁRIO AS LINHAS DE CÓDIGO COMENTADAS ABAIXO
* QUE LIBERAM AS OS ESPAÇOS DE MEMÓRIAS ALOCADAS DINAMICAMENTE.
* COM O USO DO PONTEIRO UNIQUE_PTR, OS ESPAÇOS SERÃO LIBERADOS
* AUTOMATICAMENTE QUANDO NÃO FOREM MAIS USADOS (SAIREM FORA DO ESCOPO).
*
while (scan != inteiros.end()){
delete (*scan);
(*scan) = NULL;
scan++;
}
*/
inteiros.clear();
cout << "Finalizando" << endl;
}
void Inteiros::getNumero(){
vector<unique_ptr<int>>::iterator scan = inteiros.begin();
cout << endl << "Imprimindo vetor:" << endl;
while (scan != inteiros.end())
{
cout << **scan << endl;
scan++;
}
}
void Inteiros::setNumero(){
for (int i = 1; i < 5; i++){
unique_ptr <int> x(new int);
cout << "Digite o " << i << "o número" << endl;
cin >> *x;
if (*x != 0){
inteiros.insert(inteiros.end(), (move(x)));
/*
* OBSERVE QUE FOI USADO O COMANDO "move" PARA A OPERAÇÃO DE INSERÇÃO
* ACIMA. ISTO PORQUE, O PONTEIRO UNIQUE_PTR NÃO PERMITE CÓPIA.
*
* OBSERVE TAMBÉM, O PROBLEMA QUANDO É INSERIDO UM NÚMERO IGUAL A ZERO.
* UM ESPAÇO DE MEMÓRIA FOI ALOCADO, PORÉM, NÃO FOI INSERIDO NO VETOR
* FICANDO TAMBÉM, SEM REFERÊNCIA DE ACESSO. ESTE ESPAÇO DE MEMÓRIA,
* FICARIA ALOCADO E SEM USO DURANTE TODA A EXECUÇÃO DO PROGRAMA.
* ESTE É UM CASO DE VAZAMENTO DE MEMÓRIA (memory leak).
* DEVIDO AO USO DO UNIQUE_PTR, ESSES ESPAÇOS SERÃO LIBERADOS ASSIM QUE
* ESTIVEREM FORA DO ESCOPO.
*/
}
else{
cout << "Número zero não permitido. Tente outro número." << endl;
i--;
}
}
}
int main(int argc, char** argv){
Inteiros numeros;
cout << "Digite 4 números" << endl;
numeros.setNumero();
numeros.getNumero();
return 0;
}