Код: Выделить всё
#pragma once
#include
namespace tom {
template
class unique_ptr {
public:
unique_ptr() noexcept
: ptr_(nullptr) {}
explicit unique_ptr(T* ptr) noexcept
: ptr_(ptr)
{}
~unique_ptr() {
delete ptr_;
ptr_ = nullptr;
}
// Move constructor
unique_ptr(unique_ptr&& other) noexcept : ptr_(other.ptr_) {
other.ptr_ = nullptr;
}
// Move assignment
unique_ptr& operator=(unique_ptr&& other) noexcept {
if (this != &other) {
delete ptr_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
return *this;
}
// Delete copy constructor as unique pointers can only have one owner
unique_ptr(const unique_ptr&) = delete;
// Delete copy assignment as unique pointers can only have one owner
unique_ptr& operator=(const unique_ptr&) = delete;
T& operator*() const noexcept { return *ptr_; }
T* operator->() const noexcept { return ptr_; }
T* get() const noexcept { return ptr_; }
T* release() noexcept {
return std::exchange(ptr_, nullptr);
}
void reset(T* ptr = nullptr) noexcept {
delete ptr_;
ptr_ = ptr;
}
void swap(unique_ptr& other) noexcept {
std::swap(ptr_, other.ptr_);
}
private:
T* ptr_;
};
template
unique_ptr make_unique(Args&&... args) {
T* tmp = new T(std::forward(args)...);
return unique_ptr(tmp);
}
}
Код: Выделить всё
#include
#include
class TestUniquePtr : public ::testing::Test {
protected:
void SetUp() override {
};
void TearDown() override {
};
};
struct Foo {
int x;
int y;
};
TEST_F(TestUniquePtr, Constructor)
{
Foo* foo = new Foo(1, 2);
{
tom::unique_ptr tmp(foo);
}
}
< /code>
Как я могу проверить, что память была удалена, как и
ASSERT_EQ(foo, nullptr)
Подробнее здесь: https://stackoverflow.com/questions/796 ... n-has-been