无法在没有读取访问冲突的情况下删除数组
Cannot delete array without read access violation
我最近想在不使用 C++(允许使用 C)标准库功能的情况下用 C++ 制作一个快速模拟器。因此,我使用原始指针数组来存储我的模拟器的内存。但是,我在将内存 class 移动到另一个内存 class 时遇到了读取访问冲突。欢迎所有建议。
内存class:
#ifndef MEM_HPP
#define MEM_HPP
#include <cstdint>
#include <cstddef>
namespace handle {
using num = std::uint8_t;
using size = std::size_t;
struct memory {
enum { EIGHT_BIT_MAX_MEM = 256, SIXTEEN_BIT_MAX_MEM = 65536 };
constexpr explicit memory(size max_mem) : mem_size(max_mem) {
mem = new num[max_mem];
}
constexpr memory(memory&& other) noexcept {
delete[] mem;
mem = other.mem;
mem_size = other.mem_size;
other.mem = nullptr;
other.mem_size = 0;
}
constexpr memory(const memory& other) = delete;
constexpr ~memory() {
delete[] mem;
}
constexpr memory& operator=(memory&& other) noexcept {
delete[] mem;
mem = other.mem;
mem_size = other.mem_size;
other.mem = nullptr;
other.mem_size = 0;
return *this;
}
constexpr num& operator[](num loc) {
return mem[loc];
}
constexpr size get_mem_size() const noexcept {
return mem_size;
}
num *mem;
size mem_size;
};
}
#endif /* MEM_HPP */
main.cpp:
#include <type_traits>
#include "mem.hpp"
int main() {
using namespace handle;
memory m{ memory::EIGHT_BIT_MAX_MEM };
memory other{ std::move(m) };
}
编辑:
即使我删除了将内存初始化为空指针的构造函数,我仍然遇到读取访问冲突。
delete[] mem;
是试图删除 move-constructor 中尚未分配的内存。删除该行。
我最近想在不使用 C++(允许使用 C)标准库功能的情况下用 C++ 制作一个快速模拟器。因此,我使用原始指针数组来存储我的模拟器的内存。但是,我在将内存 class 移动到另一个内存 class 时遇到了读取访问冲突。欢迎所有建议。
内存class:
#ifndef MEM_HPP
#define MEM_HPP
#include <cstdint>
#include <cstddef>
namespace handle {
using num = std::uint8_t;
using size = std::size_t;
struct memory {
enum { EIGHT_BIT_MAX_MEM = 256, SIXTEEN_BIT_MAX_MEM = 65536 };
constexpr explicit memory(size max_mem) : mem_size(max_mem) {
mem = new num[max_mem];
}
constexpr memory(memory&& other) noexcept {
delete[] mem;
mem = other.mem;
mem_size = other.mem_size;
other.mem = nullptr;
other.mem_size = 0;
}
constexpr memory(const memory& other) = delete;
constexpr ~memory() {
delete[] mem;
}
constexpr memory& operator=(memory&& other) noexcept {
delete[] mem;
mem = other.mem;
mem_size = other.mem_size;
other.mem = nullptr;
other.mem_size = 0;
return *this;
}
constexpr num& operator[](num loc) {
return mem[loc];
}
constexpr size get_mem_size() const noexcept {
return mem_size;
}
num *mem;
size mem_size;
};
}
#endif /* MEM_HPP */
main.cpp:
#include <type_traits>
#include "mem.hpp"
int main() {
using namespace handle;
memory m{ memory::EIGHT_BIT_MAX_MEM };
memory other{ std::move(m) };
}
编辑: 即使我删除了将内存初始化为空指针的构造函数,我仍然遇到读取访问冲突。
delete[] mem;
是试图删除 move-constructor 中尚未分配的内存。删除该行。