我应该总是处理参考返回向量吗?

时间:2017-02-21 13:34:16

标签: c++ vector reference stl

不确定here发生了什么:

#include <iostream>
#include <vector>

class Voice
{
public:
    double mValue = 0.0;

    Voice() { }
    Voice(const Voice &copy) {
    }    
};

class VoiceManager
{
public:
    std::vector<Voice> mVoices;

    VoiceManager() {
        mVoices = std::vector<Voice>(numVoices, Voice());   

        for (int i = 0; i < numVoices; i++) {
            mVoices[i].mValue = 100.0;
        }        
    }

private:
    int numVoices = 16;    
};

int main()
{    
    VoiceManager voiceManager;
    Voice voice = voiceManager.mVoices[2];
    std::cout << voice.mValue << std::endl;
}

我为每个mValue设置Voice,其值100[],但是当我尝试使用相同的[]运算符检索对象时,它似乎不归还那个元素?它打印0。

相反,如果我这样做:

Voice &voice = voiceManager.mVoices[2];

我终于可以看到更新后的价值。

这里发生了什么?

1 个答案:

答案 0 :(得分:2)

如评论中所示,您的复制构造函数是a)错误且b)多余的

class Voice
{
public:
    double mValue = 0.0;

    // don't provide default constructor, unless you have another constructor
    // use compiler-generated copy-constructor
};

class VoiceManager
{
    int numVoices = 16;    // move up here so that member-initialization works
public:
    std::vector<Voice> mVoices;

    VoiceManager() 
    :
        mVoices(numVoices) // member-initialize
    {
        for (int i = 0; i < numVoices; i++) {
            mVoices[i].mValue = 100.0;
        }        
    }
};

int main()
{    
    VoiceManager voiceManager;
    Voice voice = voiceManager.mVoices[2];
    std::cout << voice.mValue << std::endl;
}

Live Example

请注意,我还使用成员初始化语法对VoiceManager的构造函数进行了小的清理。

至于另一个问题:初始化

Voice voice = voicemanager.mVoice[2]; 

实际上调用了你的拷贝构造函数

Voice(voicemanager.mVoice[2]);

(此处的=符号并不意味着分配!)