首先,如果我在问题标题中没有使用正确的术语,我深表歉意。这是完全可能的。我开始学习 C++,我承认我在引用和拷贝方面遇到了非常困难的时间。引用我下面的代码,我有以下问题:

  • 在 main.c 中,传递给 Carrier.add() 函数 (*it) 的参数是引用,还是我放入 vector 中的计划对象的拷贝,或者其他什么?
  • 当这个参数被添加到运营商的计划 vector (在运营商类别中)时,是否添加了一个拷贝?由于我没有提供复制构造函数或告诉它进行复制,这是如何工作的?我认为它是自动生成的?
  • 如果太笼统请忽略。我想我的主要问题是我想/需要了解它是如何工作的,这就是我试图自己找出问题的答案时遇到问题的地方。有没有办法让 Visual Studio 以与编译器相同的方式在我的实际代码中生成构造函数,以便我可以在 Debug模式下单步执行它们以查看它是如何工作的。现在,当我调试时,我很难判断是否调用了编译器生成的复制构造函数(如果确实是这样的话)。

  • 这是我的代码:

    主文件
    #include "stdafx.h"
    #include <iostream>
    #include "Plan.h"
    #include "Carrier.h"
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    
        std::vector<Plan> plans;
    
        for (int i = 0; i < 4; ++i) {
            Plan p(i);
            plans.push_back(p);
        }
    
        Carrier c(5);
        for(std::vector<Plan>::iterator it = plans.begin(); it != plans.end(); ++it) {
                //my question is about the line directly below this comment
            c.add(*it);
        }
        return 0;
    }
    

    计划.h
    #pragma once
    
    class Plan
    {
    private:
        int id;
    public:
        Plan(int id);
    };
    

    计划.cpp
    #include "Plan.h"
    
    Plan::Plan(int i)
    {
        id = i;
    }
    

    运营商.h
    #pragma once
    #include <vector>
    class Plan;
    class Carrier
    {
    private:
        int id;
        std::vector<Plan> plans;
    public:
        Carrier(int i);
        void add(Plan p);
    };
    

    运营商.cpp
    #include "Carrier.h"
    #include "Plan.h"
    
    Carrier::Carrier(int i) {
        id = i;
    }
    
    void Carrier::add(Plan p) {
        plans.push_back(p);
    }
    

    最佳答案

    (1) 由于 Carrier::add 不通过引用获取其参数,因此传递了一个拷贝。要让它引用,请将其签名更改为

    void Carrier::add(Plan const &p);
    

    (2) 当你做 push_back 时,无论你是通过引用还是通过值/拷贝传递 Plan 都会创建一个拷贝;这是 std::vector (以及所有其他标准容器)语义的一部分。复制构造函数由编译器自动生成。

    (3)我不是VC++用户,但是编译器会生成的拷贝构造函数等价于
    Plan::Plan(Plan const &other)
     : id(other.id)  // there's only one member,
                     // but other members would be treated the same
    {}
    

    在空的正文中,您可以添加一个打印语句,指示调用了复制构造函数,但这不会防水;在某些情况下,允许 C++ 执行复制省略优化,这意味着跳过实际复制。

    关于c++ - 理解 C++ 中的引用和拷贝的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5653168/

    10-11 21:30