2013-05-11 69 views
1

我得繼續一個程序。我之前程序員所用的結構有很多:C++ std:vector < T* const>

std:vector< T* const> 

他在Visual Studio C++ 2010中寫道IST,並能編寫這一點。我使用g ++,它會導致一些編譯錯誤。

g++ -g -Wall -c -std=c++11 -pedantic -I/usr/include/SuperLU/ src/Cell.cpp -o obj/Cell.o 
In file included from src/Cell.cpp:13:0: 
src/Cell.h:81:2: warning: extra ';' [-pedantic] 
In file included from /usr/include/x86_64-linux-gnu/c++/4.7/./bits/c++allocator.h:34:0, 
       from /usr/include/c++/4.7/bits/allocator.h:48, 
       from /usr/include/c++/4.7/string:43, 
       from /usr/include/c++/4.7/bits/locale_classes.h:42, 
       from /usr/include/c++/4.7/bits/ios_base.h:43, 
       from /usr/include/c++/4.7/ios:43, 
       from /usr/include/c++/4.7/ostream:40, 
       from /usr/include/c++/4.7/iostream:40, 
       from src/Cell.cpp:2: 
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of 'struct __gnu_cxx::new_allocator<BattPackage::Leg* const>': 
/usr/include/c++/4.7/bits/allocator.h:89:11: required from 'class std::allocator<BattPackage::Leg* const>' 
/usr/include/c++/4.7/bits/alloc_traits.h:92:43: required from 'struct std::allocator_traits<std::allocator<BattPackage::Leg* const> >' 
/usr/include/c++/4.7/ext/alloc_traits.h:110:10: required from 'struct __gnu_cxx::__alloc_traits<std::allocator<BattPackage::Leg* const> >' 
/usr/include/c++/4.7/bits/stl_vector.h:76:28: required from 'struct std::_Vector_base<BattPackage::Leg* const, std::allocator<BattPackage::Leg* const> >' 
/usr/include/c++/4.7/bits/stl_vector.h:208:11: required from 'class std::vector<BattPackage::Leg* const>' 
src/Cell.h:283:39: required from here 
/usr/include/c++/4.7/ext/new_allocator.h:83:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = BattPackage::Leg* const; __gnu_cxx::new_allocator<_Tp>::const_pointer = BattPackage::Leg* const*; __gnu_cxx::new_allocator<_Tp>::const_reference = BattPackage::Leg* const&]' cannot be overloaded 
/usr/include/c++/4.7/ext/new_allocator.h:79:7: error: with '_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = BattPackage::Leg* const; __gnu_cxx::new_allocator<_Tp>::pointer = BattPackage::Leg* const*; __gnu_cxx::new_allocator<_Tp>::reference = BattPackage::Leg* const&] 

,他想用這種結構是什麼球,在那裏他可以添加和刪除的指針和操控指針的目標,但不會改變其上的對象指針所指向的向量。

據我瞭解,它不應該編譯,因爲T * const不可分配。

有誰知道它爲什麼在Visual Studio中編譯? 我可以在聲明中替換它而無需更改完整的代碼嗎?

回答

8

std::vector使用分配器爲其成員分配,重新分配和釋放內存。分配器要求僅針對類型爲T的分配器X定義,其中T是「任何非常量,非參考對象類型」(C++ 11表27)。所以使用std::vector<T* const>會給你一個未定義的行爲,因爲它使用的分配器沒有爲const元素類型定義。

你最好儘快解決這個問題。將聲明更改爲std::vector<T*>不大可能存在很多問題。

+0

那麼爲什麼VS編譯器無法檢測到這個問題。它是一個編譯器錯誤? – shivakumar 2013-05-11 12:29:55

+0

@shivakumar這是未定義的行爲。任何事情都可能發生。它只是默默地忽略它並不是一個錯誤。 – 2013-05-11 12:30:25

+0

好吧,我的想法爲什麼失敗了。 所以你認爲VS只是假設std :: vector ? – MagunRa 2013-05-11 12:32:40