久久久久久久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 入門)
主站蜘蛛池模板: 亚洲欧美日韩成人 | 成人国产精品久久久网站 | 亚洲男人在线 | 色片在线| 成人午夜又粗又硬又大 | 欧美一级精品 | 欧美日韩在线一区二区 | 成人激情视频 | 日韩在线播放视频 | 国产精品自拍一区 | 九九九久久久 | 婷婷六月综合 | 一区二区不卡视频 | 久久亚洲国产 | 日韩午夜在线 | 国产伦精品一区二区三毛 | 亚洲免费黄色 | 自由成熟xxxx色视频 | 日韩二区在线 | 欧美国产一区二区 | 欧美草草 | 国产欧美成人 | 日本69视频 | 国产无遮挡又黄又爽免费网站 | 久久精品二区 | 午夜视频网站 | 成人毛片网站 | 欧美一级特黄aa大片 | aaaa级片| 丁香久久| 日韩精品国产一区 | 日韩免费三级 | 免费在线观看黄 | 日本美女黄色 | 国内精品一区二区三区 | 四虎影视大全 | 香蕉看片| 色伊伊 | 免费的黄色网址 | 国产嫩草视频 | 欧美综合久久 |