久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

std::string::c_str() 結果的生命周期是多少?

What is the lifetime of the result of std::string::c_str()?(std::string::c_str() 結果的生命周期是多少?)
本文介紹了std::string::c_str() 結果的生命周期是多少?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

在我的一個程序中,我必須與一些使用 const char* 的遺留代碼交互.

In one of my programs, I have to interface with some legacy code that works with const char*.

假設我有一個如下所示的結構:

Lets say I have a structure which looks like:

struct Foo
{
  const char* server;
  const char* name;
};

我的上層應用只處理std::string,所以想到了用std::string::c_str()來取回const char* 指針.

My higher-level application only deals with std::string, so I thought of using std::string::c_str() to get back const char* pointers.

但是 c_str() 的生命周期是多少?

But what is the lifetime of c_str() ?

我可以在不面對未定義行為的情況下做這樣的事情嗎?

Can I do something like this without facing undefined behavior ?

{
  std::string server = "my_server";
  std::string name = "my_name";

  Foo foo;
  foo.server = server.c_str();
  foo.name = name.c_str();

  // We use foo
  use_foo(foo);

  // Foo is about to be destroyed, before name and server
}

還是我應該立即將 c_str() 的結果復制到另一個地方?

Or am I supposed to immediately copy the result of c_str() to another place ?

謝謝.

推薦答案

如果 std::string 被銷毀或非-const 字符串的成員函數被調用.因此,如果您需要保留它,通常您會想要制作它的副本.

The c_str() result becomes invalid if the std::string is destroyed or if a non-const member function of the string is called. So, usually you will want to make a copy of it if you need to keep it around.

在您的示例中,c_str() 的結果似乎是安全使用的,因為在該范圍內不會修改字符串.(但是,我們不知道 use_foo()~Foo() 可能對這些值做什么;如果他們將字符串復制到別處,那么他們應該做一個真正的復制,而不僅僅是復制char指針.)

In the case of your example, it appears that the results of c_str() are used safely, because the strings are not modified while in that scope. (However, we don't know what use_foo() or ~Foo() might be doing with those values; if they copy the strings elsewhere, then they should do a true copy, and not just copy the char pointers.)

這篇關于std::string::c_str() 結果的生命周期是多少?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

boost_1_60_0 .zip installation in windows(Windows 中的 boost_1_60_0 .zip 安裝)
How do I get console output in C++ with a Windows program?(如何使用 Windows 程序在 C++ 中獲得控制臺輸出?)
How do I calculate the week number given a date?(如何計算給定日期的周數?)
OpenCV with Network Cameras(帶有網絡攝像機的 OpenCV)
Export all symbols when creating a DLL(創建 DLL 時導出所有符號)
Getting started with OpenCV 2.4 and MinGW on Windows 7(Windows 7 上的 OpenCV 2.4 和 MinGW 入門)
主站蜘蛛池模板: 中文字幕在线日韩 | 自拍偷拍亚洲 | 夜夜狠狠擅视频 | 欧美激情一区 | 成人a级片 | 久久精品一区二区国产 | 成人三级在线 | 自由成熟xxxx色视频 | 精品粉嫩小bbwbbwbbw | 97超碰在线免费观看 | 久久精品福利 | 日本特黄一级片 | 日本在线观看 | 国产黄色一区二区 | 国产成人综合网 | 国产寡妇亲子伦一区二区三区四区 | 亚洲欧美另类在线 | 日本一区二区不卡视频 | 欧美日韩免费在线 | 日本免费毛片 | 五月伊人网 | 狠狠做深爱婷婷综合一区 | 少妇激情视频 | 天天插天天爽 | 国产专区在线播放 | 又色又爽又黄gif动态图 | 国产又黄又粗 | 在线看片a | 黄色一级大片在线免费看产 | 99视频免费 | 国产视频在线观看视频 | 婷婷国产 | av免费不卡 | 九色视频丨porny丨丝袜 | 日韩成人片 | 毛片av在线| 欧美在线观看一区 | 日本色综合| 日日夜夜综合网 | 日韩免费视频一区二区 | 成人免费公开视频 |