如何在 C++ 中将 const 引用分配给函数内的指针?
How assign const reference to pointer within function in C++?
我有一个功能
void assign(std::vector<std::vector<double>> avg, int k) {
double* ptr=&avg[k-1][0]
//other stuff, but above is only line involving "avg" variable
}
但是函数 运行 比我想要的慢,因为我通过值而不是引用传递。如果我尝试以下操作:
void assign(const std::vector<std::vector<double>>& avg, int k) {
double* ptr=&avg[k-1][0]
//other stuff
}
然后我得到错误 cannot convert from const_Ty * to double*
。如何让函数通过引用传递 avg
?
您不能直接或间接修改 const
对象。这包括它对可以修改的对象的分配 (non-const)。
有 2 个选项:使 ptr
常量,或删除参数的常量性。前者会使指针只读(这可能是好的,也可能不是),而后者会打开对更改的引用(在大多数情况下这并不是一件好事)。
你也可以考虑是否真的需要那个指针
我有一个功能
void assign(std::vector<std::vector<double>> avg, int k) {
double* ptr=&avg[k-1][0]
//other stuff, but above is only line involving "avg" variable
}
但是函数 运行 比我想要的慢,因为我通过值而不是引用传递。如果我尝试以下操作:
void assign(const std::vector<std::vector<double>>& avg, int k) {
double* ptr=&avg[k-1][0]
//other stuff
}
然后我得到错误 cannot convert from const_Ty * to double*
。如何让函数通过引用传递 avg
?
您不能直接或间接修改 const
对象。这包括它对可以修改的对象的分配 (non-const)。
有 2 个选项:使 ptr
常量,或删除参数的常量性。前者会使指针只读(这可能是好的,也可能不是),而后者会打开对更改的引用(在大多数情况下这并不是一件好事)。
你也可以考虑是否真的需要那个指针