2014-01-23 93 views
0

在下面的簡單的例子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()返回一個非常量向量?

回答

1

const

這裏的錯誤是你正在測試的方式。 is_const只是告訴你,參考類型不是const,它總是如此。

最好直接測試這些東西,例如by trying to mutate the result of d.get()

#include <vector> 
#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 { return mat_; } 
     result_type& get() { return mat_; } 
}; 

int main(int, char*[]) 
{ 
    const std::vector<double> B(5,1.0); 
    const Dumb d(B); 
    d.get().push_back(6); 
} 

// error: 
// no matching function for call to 'std::vector<double>::push_back(int) const' 

由此看來,很明顯,d.get()const std::vector<double>&

3

decltype(d.get())是參考類型;引用類型不能是const限定的(雖然它們的基礎對象類型可以),所以is_const將是錯誤的。

如果測試基礎對象類型std::remove_reference<decltype(d.get())>::type,則is_const應爲true。

相關問題