2011-06-18 113 views
1

我用boost :: interprocess :: managed_(windows_)shared_memory :: construct來構造一個持有自己類的進程間向量,該類有一個成員變量類型的std :: string和其他類型的std ::的載體,所以:boost :: interprocess - std :: string與std :: vector

class myclass 
{ 
    public: 
     myclass() 
     { 

     } 

     std::string _mystring; 
     std::vector <int> _myintvector; 
}; 

template < class _type > 
struct typedefs 
{ 
    typedef boost::interprocess::managed_windows_shared_memory  _memory; 
    typedef _memory::segment_manager        _manager; 
    typedef boost::interprocess::allocator < _type, _manager >  _allocator; 
    typedef boost::interprocess::vector < _type, _allocator >  _vector; 
}; 

typedef typedefs <myclass> tdmyclass; 

int main() 
{ 
    using namespace boost::interprocess; 

    managed_windows_shared_memory mem (open_or_create, "mysharedmemory", 65536); 
    tdmyclass::_vector * vec = mem.construct <tdmyclass::_vector> ("mysharedvector") (mem.get_segment_manager()); 
    myclass mytemp; 

    mytemp._mystring = "something"; 
    mytemp._myintvector.push_back (100); 
    mytemp._myintvector.push_back (200); 

    vec->push_back (mytemp); 

    /* waiting for the memory to be read is not what this is about, 
    so just imagine the programm stops here until everything we want to do is done */ 
} 

我只是做了這個測試,我預計既不的std :: string也沒有的std ::向量是工作,但是,如果我從另一個進程讀取它,std :: string實際上工作,它包含我分配的字符串。這讓我很驚訝。 另一側的std :: vector只能部分工作,size()返回的值是正確的,但如果我想訪問迭代器或者使用operator [],程序崩潰。

所以,我的問題是,爲什麼這樣呢?我的意思是,我從來沒有真正閱讀Visual Studio的SDK的STL實現,但不是std :: string只是一個具有適合字符串的額外函數的std :: vector?難道他們都不使用std :: allocator - 這意味着,std :: string和std :: vector在共享內存中不起作用嗎?

谷歌搜索這不會真正導致除了boost :: interprocess :: vector之外的任何東西,那不是我搜索的東西。所以我希望有人能給我一些關於發生什麼事情的細節^^

PS:如果我在上面的代碼中做了一個錯字,請原諒我,我現在就寫在這個頁面編輯器中,並且我也有點用於我的IDE的自動完成^^

回答

6

std::string因爲您的標準庫實現使用小字符串優化(SSO)而起作用。這意味着字符串"something"的值被複制到字符串對象本身中,沒有任何動態內存分配。因此,您可以從其他進程中讀取它。對於更長的字符串(嘗試30個字符),它不會工作。

std::vector不起作用,因爲它不允許按標準使用SSO。它在第一個進程的地址空間中分配內存,但這個內存不能被其他進程訪問。 .size()的作品,因爲它存儲裏面的矢量本身,作爲一個成員。

P.S. stringvector之間有很多不同之處。最重要的一個,也是最少提到的那個,就是string is not a container from standard's point of view

+0

沒錯。所以它不適用於更長的字符串。檢查它:_) – sehe

+0

非常感謝^^和是我忘記提及std :: vector的行爲完全符合我的預期^^但是我從來沒有聽說過任何來自SSO的^^ – Andy

相關問題