Re: [問題] 一個有意思的問題 vector <const int>

看板C_and_CPP作者 (燒賣)時間15年前 (2009/12/19 17:46), 編輯推噓2(2014)
留言16則, 5人參與, 最新討論串3/3 (看更多)
※ 引述《spider391 (小乖)》之銘言: : code 很短我就直接貼了 : ====================================================== : #include <iostream> : #include <vector> : using namespace std; : int main() : { : vector<const int> tmp; : tmp.push_back(99); : tmp[0] = 10; // 很神奇這裡竟然可以允許更動 : cout << "tmp[0] is: " << tmp[0] << endl; : } : ======================================================= : 我讓vector內的元素為 const : 但 temp[0] 他竟然允許賦值 !! : 請問各位高手有什麼想法 <( ̄oo, ̄)/ : 補充一下: : 這段 code 在 Visual Studio 2005 可以跑 : 我在 cygwin 上的 g++ (3.4.4) 上 compile 則會出現 compiler error!! : 謝謝 在 C++ 標準裡對於 Container Library 的說明有包含這一段: The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types. 至少必須符合可用複製建構式和可指派(assign)兩個要求, C/C++對於非標準的行為大多數是未定義的, 所以在不同編譯器上看運氣會有不同反應。 我發現 Wikipedia 也有把這一段寫進去 http://en.wikipedia.org/wiki/Vector_(C%2B%2B)#Design The vector template can be instantiated with any type that fulfills the CopyConstructible and Assignable requirements -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.104.246

12/20 03:06, , 1F
其實那些 concept 在 STL 的書都有寫了,只是很多人都不看
12/20 03:06, 1F

12/20 03:06, , 2F
就先用,使用工具之前也好歹要讀讀操作手冊啊。
12/20 03:06, 2F

12/20 11:20, , 3F
問題是 int 是 CopyConstructible 且 Assignable
12/20 11:20, 3F

12/20 14:19, , 4F
但 const int 要說它是 Assignable 有點怪...
12/20 14:19, 4F

12/20 14:20, , 5F
const int 的那種指定值的方法反而像是 copy constructed
12/20 14:20, 5F

12/20 14:26, , 6F
const int本來就不是assignable 所以這是未定義行為
12/20 14:26, 6F

12/20 14:27, , 7F
既然是未定義行為 g++和VC2005的作法都是合標準的..
12/20 14:27, 7F

12/20 14:27, , 8F
錯的是寫出未定義行為的programmer XD
12/20 14:27, 8F

12/20 14:35, , 9F
我在想的是原 PO 是不是想知道 g++ 跟 VC 分別是如何實現的
12/20 14:35, 9F

12/20 14:36, , 10F
const 變數產生的時候就跟值 bind 完了,照理說連 push_back
12/20 14:36, 10F

12/20 14:37, , 11F
都不行才對
12/20 14:37, 11F

12/20 16:06, , 12F
我自己有寫個簡單的 vector 去模擬,沒有 Allocator
12/20 16:06, 12F

12/20 16:08, , 13F
我用 vecotr<const int> 跑出的結果是
12/20 16:08, 13F

12/20 16:08, , 14F
you cannot assign to a variable that is const
12/20 16:08, 14F

12/20 16:09, , 15F
這是符合我預期的想法,而 g++ 的 error
12/20 16:09, 15F

12/20 16:10, , 16F
是在 new_allocator.h 'const void*' to 'void*'
12/20 16:10, 16F
文章代碼(AID): #1BBH6G_X (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BBH6G_X (C_and_CPP)