std::字符串的生存期作为参数传递
lifetime of std::string passed as argument
我想确保我理解正确。 在下面的 c++ 函数中,三个实例将创建 std::string:
- 一个用于 caller() 中的 s1,通过我认为称为赋值构造函数
- 一个用于 callee() 函数的 s2 参数,通过它的复制构造函数
- 一个用于 S3 通过其复制构造函数
我说的对吗? 如果是这样,当这三个实例超出范围时,它们是否会被清理? 我并不是真的在问这是否是好代码,只是我的理解是否正确。
void caller(void) {
std::string s1 = "hi";
callee(s1);
}
void callee(std::string s2) {
std::string s3 = s2;
}
不要假设副本在任何地方都是制作的。在实践中,复制省略比您想象的更频繁地发生。编译器可以自由地优化多余的副本,即使副本有副作用:
void caller(void) {
std::string s1 = "hi";
//theoretically, s1 is copied here
//in practice, the compiler will optimize the call away
functionCallee(s1);
}
void callee(std::string s2) {
//although s2 is passed by value, it's probably no copy was created
//most likely, it's exactly the same as s1 from the calling context
std::string s3 = s2;
}
此外,如果方法是内联的,并且编译器检测到没有发生副作用,则甚至可能不会创建字符串。
你几乎是对的。
可以创建三个或四个字符串(取决于是否省略了s1
的构造),并且在每种情况下都调用构造函数来构造它们。尽管表面上看起来,但没有调用任何分配运算符。
void caller(void) {
//A temporary std::string is constructed with the
//basic_string(const CharT* s, const Allocator& alloc = Allocator())
//constructor.
//(In the call, `s` is initialized to point to the first element of "hi".)
//This temporary is then move constructed in to s1.
//The move constructor is
//basic_string(basic_string&& other)
//This move construction may be elided.
std::string s1 = "hi"; //At the end of the full expression (ie, at the semicolon)
//the lifetime of the temporary string ends (unless
//the construction of s1 is elided, in which
//case the temporary becomes s1, and its lifetime ends
//with s1).
//s2 is copy constructed from s1
//The copy constructor is
//basic_string(const basic_string& other)
callee(s1);
//the lifetime of s1 ends
}
void callee(std::string s2) {
//s3 is copy constructed from s2
std::string s3 = s2;
//the lifetime of s3 ends
//the lifetime of s2 ends
}
相关文章:
- 将字符串数组作为函数参数传递
- 如何通过C++在Python函数中传递字符串参数
- 当数组大小在C++中未知时,如何在运行时将对字符串数组的引用作为函数参数传递?
- 如何将从第 2 个字符开始的字符串作为函数中的参数传递以进行递归,并约束数据 tiee 是函数中的字符串?
- C++ _beginthread不能将字符串作为参数传递
- 如何将 std::string 作为构造函数参数传递,并将其保存的 C 字符串存储在 void 指针中?
- Pybind11:将字符串*参数传递给构造函数
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 在 c++ 中调用将字符串作为参数传递的函数时出错
- 无法将字符串参数传递到构造函数中?
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 如何在C++中将字符串的动态二维数组作为参数传递
- 减少将参数传递给函数所需的字符串流操作的详细程度
- 如何将字符串数组作为函数参数传递
- 将字符串作为系统参数C 传递
- 将字符串作为命令行参数传递
- 线程传递字符串参数的布尔函数
- 试图将字符串作为类的参数传递,但在C++中它被识别为字符数组
- 如何确保当无效字符串作为参数传递时posix_time_zone构造函数不会崩溃
- C++ 不能将公共 const 字符串成员作为参数传递给同一类的成员函数