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

赋值返回值何时产生副本?C++代码场景疑问与分析

C++对象初始化与副本/引用问题

问题

  1. 下方int main中有6行变量创建并初始化的代码,哪些场景下赋值操作会产生副本?
  2. 对于sixthMap,使用带&的自动类型推导,但调用的函数也返回引用,是否/可能出现异常情况?
std::unordered_map<std::string, std::vector<std::string>>
createStdObject()
{
    std::unordered_map<std::string, std::vector<std::string>> newUnorderedMap
    {
        {"A", {"first", "vector", "in", "map"}}, 
        {"B", {"second", "vector", "in", "map"}}
    };

    return newUnorderedMap;
}

std::unordered_map<std::string, std::vector<std::string>>&
createStdObjectWithReference()
{
    std::unordered_map<std::string, std::vector<std::string>> newUnorderedMap
    {
        {"A", {"first", "vector", "in", "map"}}, 
        {"B", {"second", "vector", "in", "map"}}
    };

    return newUnorderedMap;
}

int main()
{
    std::unordered_map<std::string, std::vector<std::string>> firstMap = createStdObject();
    std::unordered_map<std::string, std::vector<std::string>> secondMap = createStdObjectWithReference();
    
    const auto thirdMap = createStdObject();
    const auto& fourthMap = createStdObject();

    const auto fifthMap = createStdObjectWithReference();
    const auto& sixthMap = createStdObjectWithReference();
    
}

(注:修正了原代码中模板参数缺失、括号未闭合、函数调用名笔误的语法问题,不影响核心问题讨论)

个人猜测(基于有限知识)

  • firstMap和thirdMap可能是createStdObject()返回值的副本;
  • 其他场景不会产生副本,而是执行移动/交换操作;
  • sixthMap的auto声明中的&会被忽略,类型和行为与fifthMap一致。

但编译时可见所有返回值无需复制,理应都执行移动赋值。


内容的提问来源于stack exchange,提问作者Numinous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:40:09