这是否会导致未定义的行为或内存泄漏?

时间:2016-04-25 20:55:29

标签: c++ c++11 memory-management memory-leaks

我们有一个简单的类,它使用placement new为指针分配内存,然后在适当的位置构造值。一切都好(我希望)。

兴趣点是移动构造函数。当我交换两个对象之间的指针(让它们称为A和B,A由B构造)时,A中的指针现在是拥有指针,B中的指针不是拥有指针。那么A中的析构函数将处理清理,但是B中的析构函数会阻塞,因为它会尝试删除一个非拥有指针(不用new分配)。我通过添加if语句来检查大小是否为零(表示尚未创建的对象)。

然而,当我编译并运行它时,控制台就冻结了。我似乎无法找到问题所在。

#include <iostream>
#include <cstddef>
#include <utility>

using std::size_t;

template<typename T>
class foo
{
private:
    T* p = nullptr;
    size_t sz = 0;

public:
    foo(T* first, T* last)
        : p(nullptr), sz(static_cast<size_t>(last - first))
    {
        p = static_cast<T*>(::operator new(sz * sizeof(T)));

        for (size_t i = 0; first != last; ++first, ++i) {
            ::new(static_cast<void*>(&p[i])) T(*first);
        }
    }

    foo(foo&& rhs) noexcept
    {
        std::swap(p, rhs.p);
        std::swap(sz, rhs.sz);
    }

    ~foo()
    {
        if (sz != 0)
        {
            for (size_t i = 0; i < sz; ++i) {
                (&p[i])->~T();
            }
            ::operator delete(static_cast<void*>(p));
        }
    }
};

int main()
{
    int arr[5] = { 1, 2, 3, 4, 5 };
    foo<int> f(arr, arr + 5);
    foo<int> f2 = std::move(f);
}

0 个答案:

没有答案
相关问题