std::array 的项目被无意中脱离上下文更改
Items of std::array are changed unintentionally out of context
我正在尝试通过构造函数将数组的引用传递给 class 对象,并操作该对象中的项目。
但是,恐怕数组中的这些项目在到达下面 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;
}
- 在通过副本传递数组的情况下,它工作正常。
感谢您的关注。
构造函数
MySort(T n) : _n(n)
{
_s = _n.size();
}
在这里您设置 _n
以引用一个输入对象,该对象将在离开构造函数时被销毁。这是普通的 UB。
要修复它写
MySort(T& n) : _n(n)
{
_s = _n.size();
}
在构造函数 MySort(T n)
中,您正在制作数组的副本,然后存储对副本的引用,但随后副本超出范围,因此您有一个悬空引用。
如果要使用引用,应传递对原始对象的引用,MySort(T &n)
,并确保原始对象在 MySort 对象的生命周期内始终在范围内。
我正在尝试通过构造函数将数组的引用传递给 class 对象,并操作该对象中的项目。 但是,恐怕数组中的这些项目在到达下面 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;
}
- 在通过副本传递数组的情况下,它工作正常。
感谢您的关注。
构造函数
MySort(T n) : _n(n)
{
_s = _n.size();
}
在这里您设置 _n
以引用一个输入对象,该对象将在离开构造函数时被销毁。这是普通的 UB。
要修复它写
MySort(T& n) : _n(n)
{
_s = _n.size();
}
在构造函数 MySort(T n)
中,您正在制作数组的副本,然后存储对副本的引用,但随后副本超出范围,因此您有一个悬空引用。
如果要使用引用,应传递对原始对象的引用,MySort(T &n)
,并确保原始对象在 MySort 对象的生命周期内始终在范围内。