c++ - 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;
}
- 在通过副本传递数组的情况下,它可以正常工作。
感谢您的关注。
解决方案
构造函数
MySort(T n) : _n(n)
{
_s = _n.size();
}
在这里,您设置_n
引用一个输入对象,该对象将在离开构造函数时被销毁。这是普通的UB。
要修复它写
MySort(T& n) : _n(n)
{
_s = _n.size();
}
推荐阅读
- python - 无法安装 python3-setuptools
- azure - 检测密钥的 Application Insights 错误
- permissions - UWSGI 日志轮换出现错误:“父目录具有不安全的权限”
- javascript - 井字游戏应用程序中的撤消按钮使用 ReactJS
- asp.net - 用于连接 SQL Server 并以 JSON 格式返回响应的 Web API
- bash - 一行中的多个 awks
- arrays - 使用多字符分隔符将字符串拆分为数组
- r - 在 r 中的值内过滤 n char
- node.js - apollo-angular error // 角度项目无法编译
- php - 在php中的提交按钮后打印账单发票