在C ++中保证临时的生存期? [英] Guaranteed lifetime of temporary in C++?
问题描述
C ++为在函数调用中创建但不用作参数的临时变量的生命周期提供了保证吗?下面是一个示例类:
class StringBuffer
{
public:
StringBuffer(std: :string& str):m_str(str)
{
m_buffer.push_back(0);
}
〜StringBuffer()
{
m_str =& m_buffer [0];
}
char * Size(int maxlength)
{
m_buffer.resize(maxlength + 1,0);
return& m_buffer [0];
}
private:
std :: string& m_str;
std :: vector< char> m_buffer;
};
以下是使用方法:
//这是来自一个旧的API,不能更改
void GetString(char * str,int maxlength);
std :: string mystring;
GetString(StringBuffer(mystring).Size(MAXLEN),MAXLEN);
什么时候会调用临时StringBuffer对象的析构函数?是
:- 在调用GetString之前?
- GetString返回后
- 编译器依赖?
我知道C ++保证本地临时变量是有效的,
感谢。
在全表达式的结尾处调用那种临时的析构函数。这是最外层的表达式,不是任何其他表达式的一部分。这是在你的情况下,函数返回并且值被求值之后。所以,它会工作所有好的。
这实际上是表达式模板的工作原理:它们可以在表达式中保持对那种临时性的引用
e = a + b * c / d
因为每个临时变量都会持续到表达式
x = y
完全评估。这在标准中 12.2临时对象
中非常简洁地描述。
Does C++ provide a guarantee for the lifetime of a temporary variable that is created within a function call but not used as a parameter? Here's an example class:
class StringBuffer
{
public:
StringBuffer(std::string & str) : m_str(str)
{
m_buffer.push_back(0);
}
~StringBuffer()
{
m_str = &m_buffer[0];
}
char * Size(int maxlength)
{
m_buffer.resize(maxlength + 1, 0);
return &m_buffer[0];
}
private:
std::string & m_str;
std::vector<char> m_buffer;
};
And here's how you would use it:
// this is from a crusty old API that can't be changed
void GetString(char * str, int maxlength);
std::string mystring;
GetString(StringBuffer(mystring).Size(MAXLEN), MAXLEN);
When will the destructor for the temporary StringBuffer object get called? Is it:
- Before the call to GetString?
- After GetString returns?
- Compiler dependent?
I know that C++ guarantees that a local temporary variable will be valid as long as there's a reference to it - does this apply to parent objects when there's a reference to a member variable?
Thanks.
The destructor for that sort of temporaries is called at the end of the full-expression. That's the most outer expression which is not part of any other expression. That is in your case after the function returns and the value is evaluated. So, it will work all nice.
It's in fact what makes expression templates work: They can keep hold references to that sort of temporaries in an expression like
e = a + b * c / d
Because every temporary will last until the expression
x = y
Is evaluated completely. It's quite concisely described in 12.2 Temporary objects
in the Standard.
这篇关于在C ++中保证临时的生存期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!