You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

以下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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:36:03