[英]boost::interprocess — std::string vs. std::vector
我用boost :: interprocess :: managed_(windows_)shared_memory :: construct構造一個擁有自己類的進程間向量,該類具有一個成員變量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 :: vector都不起作用,但是,如果我從另一個進程中讀取它,則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的^^
std::string
之所以有效,是因為您的標准庫實現使用小字符串優化(SSO)。 這意味着將字符串"something"
值復制到字符串對象本身,而沒有任何動態內存分配。 因此,您可以從其他過程中讀取它。 對於更長的字符串(嘗試輸入30個字符),它將不起作用。
std::vector
不起作用,因為標准不允許使用SSO。 它在第一個進程的地址空間中分配內存,但是其他進程無法訪問此內存。 .size()
之所以起作用,是因為它作為成員存儲在向量本身中。
PS在string
和vector
之間有很多區別。 從標准的角度來看 ,最重要的也是最不被提及的是string
不是容器 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.