首页 > 解决方案 > std::array 的项目无意中脱离上下文而更改

问题描述

我正在尝试通过构造函数将数组的引用传递给类对象,并操作该对象中的项目。但是,恐怕数组中的这些项目在到达下面的 MySort::sort() 开头之后就会改变。(在进入 MySort::sort() 之前未更改)

#include <iostream>
#include <utility>
#include <array>

using namespace std;

template <typename T>
struct MySort
{
    T &_n;
    size_t _s;

public:
    MySort(T n) : _n(n)
    {
        _s = _n.size();
    }

    void sort()
    {
        for (size_t i = 0; i < _s - 1; i++)
        {
            for (size_t j = i + 1; j < _s; j++)
            {
                if (_n[i] > _n[j])
                    std::swap(_n[i], _n[j]);
            }
        }
        cout << "teste" << endl;
    }
    friend ostream &operator<<(ostream &ost, const MySort &c)
    {
        for (size_t i = 0; i < c._s; i++)
            ost << c._n[i];
        return ost;
    }
};

int main(int argc, const char **argv)
{
    array<int, 5> numbers{2, 5, 1, 7, 3};

    MySort<array<int, 5>> bubble{numbers};
    bubble.sort();
    cout << bubble << endl;

    return 0;
}

感谢您的关注。

标签: c++referencestl

解决方案


构造函数

MySort(T n) : _n(n)
{
    _s = _n.size();
}

在这里,您设置_n引用一个输入对象,该对象将在离开构造函数时被销毁。这是普通的UB。

要修复它写

MySort(T& n) : _n(n)
{
    _s = _n.size();
}

推荐阅读