AdvC++ - różnica międfzy starą alokacją a smart pointerami
This commit is contained in:
parent
b57df4dcee
commit
24943a4282
3 changed files with 42 additions and 1 deletions
|
|
@ -12,3 +12,12 @@ set(SRC_LIST
|
|||
add_executable(${PROJECT_NAME} ${SRC_LIST})
|
||||
target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra)
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR})
|
||||
project(Resource2)
|
||||
|
||||
set(SRC_LIST
|
||||
resource2.cpp
|
||||
)
|
||||
|
||||
add_executable(${PROJECT_NAME} ${SRC_LIST})
|
||||
target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra)
|
||||
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR})
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ int main(int argc, char* argv[]) {
|
|||
delete rsc;
|
||||
} catch (std::logic_error& e) {
|
||||
std::cout << e.what() << '\n';
|
||||
// wyciek pamięci bo nie ma delete
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
|
|
|||
31
AdvancedCppV2/Presentation/exercises/resource/resource2.cpp
Normal file
31
AdvancedCppV2/Presentation/exercises/resource/resource2.cpp
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
class Resource {
|
||||
public:
|
||||
void use(const char* N) {
|
||||
std::cout << "Using resource. Passed " << *N << '\n';
|
||||
if (*N == 'd') {
|
||||
throw std::logic_error("Passed d. d is prohibited.");
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
if (argc != 2) {
|
||||
std::cerr << "You need to pass 1 argument" << '\n';
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
const char* arg = argv[1];
|
||||
std::unique_ptr<Resource> rsc = nullptr;
|
||||
|
||||
try {
|
||||
rsc = std::make_unique<Resource>();
|
||||
rsc->use(arg);
|
||||
} catch (std::logic_error& e) {
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
Loading…
Reference in a new issue