0

我有一个名为Solution定义如下的类。我只包含了相关代码,并没有编写自定义复制或赋值运算符。

class Solution {

public:

    Solution() {
        stream.setNewSeed(seedShift+static_cast<long>(12345));
        ++seedShift;
    }

    RandomNumberStream stream;

private:

    static long seedShift = 0;
};

这里的重点是我希望每个新实例Solution都有不同的随机数流。这行得通。

然而,问题是在某些地方我Solution从 a复制一个实例std::vector<Solution>,稍微修改它,然后将副本推送到同一个std::vector<Solution>. 发生这种情况时,我有两个Solution具有相同随机数种子的实例,灾难随之而来。

如何使stream.setNewSeed(seedShift+static_cast<long>(12345));and++seedShift;语句在Solution推送到向量上的复制实例中运行?

4

2 回答 2

1

重载赋值运算符。注意 - 这也意味着当您从向量中读取值和/或复制向量本身时,随机数种子也会再次发生变化。

class Solution {

public:

    Solution() {
        stream.setNewSeed(seedShift+static_cast<long>(12345));
        ++seedShift;
    }

    Solution& operator=(Solution& other)
    {
        stream.setNewSeed(seedShift+static_cast<long>(12345));
        ++seedShift;


        x = other.x;
        y = other.y;
        z = other.z;


        return *this;
    }

    RandomNumberStream stream;

private:

    static long seedShift = 0;
};
于 2013-04-15T04:26:04.233 回答
1

推入 avector将使用复制构造函数(或移动构造函数,但我们将使其简单并假设它现在使用复制构造函数)。这有签名:

Solution(const Solution& rhs);

然后,您可以相当简单地实现此逻辑:

Solution(const Solution& rhs)
{ 
     stream.setNewSeed(seedShift + 12345L);
     ++seedShift;
}

请注意,如果您实现了这一点,您可能还应该实现复制赋值运算符:

Solution& operator=(const Solution& rhs)
{
    if(this != &rhs) {
        stream.setNewSeed(seedShift+static_cast<long>(12345));
        ++seedShift;
    }
    return *this;
}
于 2013-04-15T04:29:28.247 回答