在下面的簡單的例子const成員返回作爲非const
#include <vector>
#include <type_traits>
#include <typeinfo>
#include <iostream>
class Dumb {
public:
typedef const std::vector<double> result_type;
private:
result_type mat_;
public:
Dumb(const result_type& mat) : mat_(mat) {}
const result_type& get() const {
std::cout << "const return" << std::endl;
return mat_;
}
result_type& get() {
std::cout << "non-const return" << std::endl;
return mat_;
}
};
int main(int,char*[]){
const std::vector<double> B(5,1.0);
const Dumb d(B);
d.get();
std::cout << "d " << typeid(d).name() << " "
<< std::is_const<decltype(d)>::value << std::endl;
std::cout << "d.get() " << typeid(d.get()).name() << " "
<< std::is_const<decltype(d.get())>::value << std::endl;
}
其產生輸出
const return
d N12_GLOBAL__N_14DumbE 1
d.get() NSt3__16vectorIdNS_9allocatorIdEEEE 0
例如
const return
double (anonymous namespace)::Dumb 1
d.get() std::__1::vector<double, std::__1::allocator<double> > 0
爲什麼d.get()
返回一個非常量向量?