以下C++代码调用的是move构造函数还是copy构造函数?
问题解答
结论
既不会调用std::string的拷贝构造函数,也不会调用移动构造函数,而是直接调用std::string接收C风格常量字符串(const char*)的普通构造函数来构造形参对象。
原理说明
- 你传入的实参是字符串字面量
"I am good",它的原生类型是const char[10],可以隐式转换为const char*,本身不属于std::string类型,不存在可供拷贝或者移动的已有std::string对象。 - 函数形参要求是
std::string类型,编译器会自动触发隐式转换:直接调用std::string(const char*)构造函数,在形参的内存地址上直接构造目标对象,整个过程没有std::string的拷贝、移动操作发生。
验证方法
你可以修改代码打印构造调用记录来验证,示例如下:
#include <iostream> #include <string> using namespace std; // 自定义继承类打印构造调用 class MyString : public string { public: using string::string; MyString(const char* s) : string(s) { cout << "调用const char*构造函数" << endl; } MyString(const MyString& s) : string(s) { cout << "调用拷贝构造函数" << endl; } MyString(MyString&& s) noexcept : string(std::move(s)) { cout << "调用移动构造函数" << endl; } }; void called(MyString value) { cout << "Value is " << value << endl; } int main() { called("I am good"); return 0; }
运行后只会打印调用const char*构造函数,不会出现拷贝、移动构造的日志。
内容的提问来源于stack exchange,提问作者Sathish
相关产品推荐
相关产品推荐

