从析构函数访问模板类构造函数的参数,可以吗?
Access to the template class constructor's parameter from the destructor, is it possible?
我想看看如何从析构函数访问构造函数的参数。在此示例中,我想从构造函数修改参数并在析构函数中恢复它。
template<typename T>
class sorted_array_view {
public:
sorted_array_view(T* givenArray,size_t size) {
for( int idx = 0; idx < size; ++idx){
data.push_back(givenArray[idx]);
originaldata.push_back(givenArray[idx]);
}
std::sort(data.begin(), data.end());
for(int idx =0; idx<size; ++idx){
givenArray[idx] = data.at(idx);
}
}
~sorted_array_view(){
for(int idx =0; idx<size; ++idx){
givenArray[idx] = originaldata.at(idx);
}
}
private:
std::vector<T> data;
std::vector<T> originaldata;
};
但是我在析构函数中'givenArray' was not declared in this scope
错误。如何访问givenArray
?
只需givenArray
成为类的数据成员即可。
然后析构函数(和任何其他成员函数(将有权访问它。
PS:将析构函数中的size
更改为originaldata.size()
,如果它们的值相同(从您的代码中似乎是这种情况(。否则,您也需要size
才能成为数据成员。
使用更多的 STL,你的代码甚至可以变成
#include <iostream>
#include <vector>
#include <algorithm>
template<typename T>
class sorted_array_view {
public:
sorted_array_view(T* const givenArray, size_t size)
: data(givenArray, givenArray + size)
, originaldata(givenArray, givenArray + size)
, givenArray(givenArray)
{
std::sort(data.begin(), data.end());
std::copy(std::cbegin(data), std::cend(data), givenArray);
}
~sorted_array_view() {
std::copy(std::cbegin(originaldata), std::cend(originaldata), givenArray);
}
private:
std::vector<T> data;
std::vector<T> const originaldata;
T* const givenArray;
};
#include <array>
#include <iostream>
int main()
{
std::array<int, 5> givenArray = { 4, 3, 5, 1, 2 };
{
sorted_array_view<int> sortTemp(&givenArray[0], givenArray.size());
for (const auto& el : givenArray) std::cout << el << " "; std::cout << "n";
}
for (const auto& el : givenArray) std::cout << el << " "; std::cout << "n";
}
输出:
1 2 3 4 5
4 3 5 1 2
现场示例
但是在你的构造函数/析构函数中做太多是危险的。不能从析构函数引发异常。编辑:见彼得的评论。
通常,在一个类中,如果要从另一个成员函数访问一个成员函数的参数,则需要将该参数存储在类中。
总的来说,简化你的代码,它提供了:
template<typename T>
struct sorted_array_view
{
sorted_array_view(T* array, std::size_t size)
: original_content{array, array+size}, original_container{array}
{
std::sort(array, array+size);
}
~sorted_array_view()
{
std::copy(begin(original_content), end(original_content), original_container);
}
private:
std::vector<T> original_content;
T* original_container;
};
完整演示:http://coliru.stacked-crooked.com/a/2958a997404bfaf9
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?