AdvC++ - różnica międfzy starą alokacją a smart pointerami

This commit is contained in:
Sasza Stanczew 2024-04-26 15:46:09 +02:00
parent b57df4dcee
commit 24943a4282
3 changed files with 42 additions and 1 deletions

View file

@ -12,3 +12,12 @@ set(SRC_LIST
add_executable(${PROJECT_NAME} ${SRC_LIST}) add_executable(${PROJECT_NAME} ${SRC_LIST})
target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra) target_compile_options(${PROJECT_NAME} PUBLIC -Wall -Werror -Wpedantic -Wextra)
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_SOURCE_DIR}) 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})

View file

@ -27,6 +27,7 @@ int main(int argc, char* argv[]) {
delete rsc; delete rsc;
} catch (std::logic_error& e) { } catch (std::logic_error& e) {
std::cout << e.what() << '\n'; std::cout << e.what() << '\n';
// wyciek pamięci bo nie ma delete
} }
return 0; return 0;
} }

View 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;
}