如何在c语言引用string,C++ 为什么在返回字符串的函数上调用std :: string.c_str()不起作用?...

getString() would return a copy of str (getString() returns by value);

这是正确的.

thus, the copy of str would stay “alive” in main() until main() returns.

不,返回的副本是一个临时的std :: string,它将在创建它的语句的末尾被销毁,即在std :: cout<

std::string s1 = getString(); // s1 will be copy initialized from the temporary

const char* cStr1 = s1.c_str();

std::cout << cStr1 << std::endl; // safe

const std::string& s2 = getString(); // lifetime of temporary will be extended when bound to a const lvalue-reference

const char* cStr2 = s2.c_str();

std::cout << cStr2 << std::endl; // safe

std::string&& s3 = getString(); // similar with above

const char* cStr3 = s3.c_str();

std::cout << cStr3 << std::endl; // safe

以下是[The.C .Programming.Language.Special.Edition] 10.4.10临时对象[class.temp]]的解释:

Unless bound to a reference or used to initialize a named object, a

temporary object is destroyed at the end of the full expression in

which it was created. A full expression is an expression that is

not a subexpression of some other expression.

The standard string class has a member function c_str() that

returns a C-style, zero-terminated array of characters (§3.5.1, §20.4.1). Also, the operator + is defined to mean string concatenation.

These are very useful facilities for strings . However, in combination they can cause obscure problems.

For example:

06001

Probably, your first reaction is “but don’t do that,” and I agree.

However, such code does get written, so it is worth knowing how it is

interpreted.

A temporary object of class string is created to hold s1 + s2 . Next, a pointer to a C-style string is extracted from that object. Then – at the end of the expression – the temporary object is deleted. Now, where was the C-style string allocated? Probably as part of the temporary object holding s1 + s2 , and that storage is not guaranteed to exist after that temporary is destroyed. Consequently, cs points to deallocated storage. The output operation cout << cs might work as expected, but that would be sheer luck. A compiler can detect and warn against many variants of this problem.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值