获取有关调试断言的错误失败:表达式:“(__ Ptr_user&(_ BIG_ALLOCATION_ALIGNMENT -1))== 0” && 0

问题描述 投票:0回答:1

我有一个简单的例子,它模仿一个向量。我得到调试断言失败:

C:\program files (x86)\microsoft visual studio 14.0\vc\include\xmemory0 Line: 100
Expression: "(_Ptr_user &(_BIG_ALLOCATION_ALIGNMENT -1)) == 0" && 0

这是我的例子。StrVec.h:

#pragma once
#include <string>
#include <memory>

class StrVec
{
public:
   StrVec();
   StrVec(const StrVec &);
   StrVec &operator=(const StrVec &);
   ~StrVec();

   void push_back(const std::string &s);
   size_t size() const;
   size_t capacity() const;
   std::string *begin() const;
   std::string *end() const;

private:
   void check_volume();
   void reallocate();
   void free();
   std::pair<std::string *, std::string *>
   alloc_n_copy(const std::string *, const std::string *);

   std::string *elements;
   std::string *first_free;
   std::string *cap;
   static std::allocator<std::string> alloc;
};

StrVec.cpp:

#include "stdafx.h"
#include "StrVec.h"

std::allocator<std::string> StrVec::alloc = std::allocator<std::string>();

StrVec::StrVec()
   : elements(nullptr), first_free(nullptr), cap(nullptr) {}

StrVec::StrVec(const StrVec &s) {
   auto newBegin = alloc_n_copy(s.begin(), s.end());
   elements = newBegin.first;
   cap = first_free = newBegin.second;
}

StrVec &StrVec::operator=(const StrVec &rhs) {
   auto newBegin = alloc_n_copy(rhs.begin(), rhs.end());
   free();
   elements = newBegin.first;
   cap = first_free = newBegin.second;
   return *this;
}

StrVec::~StrVec(){
   free();
}

std::pair<std::string *, std::string *>
StrVec::alloc_n_copy(const std::string *b, const std::string *e) {
   auto newMem = alloc.allocate(e - b);
   return{ newMem, std::uninitialized_copy(b, e, newMem) };
}

void StrVec::reallocate() {
   size_t newSize = size() ? 2 * size() : 1;
   auto newBegin = alloc.allocate(newSize);
   auto newPos = newBegin;
   auto oldBegin = elements;
   for (size_t i = 0; i < size(); ++i) {
      alloc.construct(newPos++, std::move(*oldBegin++));
   }
   free();
   elements = newBegin;
   first_free = newPos;
   cap = newBegin + newSize;
}

size_t StrVec::size() const {
   return first_free - elements;
}

size_t StrVec::capacity() const {
   return cap - elements;
}

void StrVec::push_back(const std::string &s) {
   check_volume();
   alloc.construct(first_free++, s);
}

std::string *StrVec::begin() const {
   return elements;
}

std::string *StrVec::end() const {
   return first_free;
}

void StrVec::check_volume() {
   if (size() == capacity()) reallocate();
}

void StrVec::free() {
   if (elements) {
      for (auto p = first_free; p != elements; --p) {
         alloc.destroy(p);
      }
      alloc.deallocate(elements, cap - elements);
   }
}

main.cpp:

int main()
{
   StrVec a;
   a.push_back("abc");
   StrVec b;
   b = a;

   return 0;
}

我已逐步完成代码。返回主函数时失败。我认为这可能是超出范围的错误,但是我无法找到所跨越的边界。

谢谢

c++ allocator
1个回答
0
投票

应该是destroy(—p)而不是destroy(p—)。销毁销毁未初始化的内存会导致错误。

© www.soinside.com 2019 - 2024. All rights reserved.