将类向量传递给构造函数时的样式建议[关闭]

问题描述 投票:0回答:0

当我必须将一个类传递给构造函数时,我通常更喜欢使用引用(请参阅示例中的 PassSingleClassByRef)。

但是当我必须传递类向量时该怎么办? PassVectorClassByPtr 是最优雅、最安全的方法吗?我应该更喜欢 unique_ptr 吗?

class A {
public:
    double get() { return 1; }
};

class PassSingleClassByRef {
public:
    PassSingleClassByRef(const A& a) : m_a(a) {
        std::cout << m_a.get() << "\n";
    }
protected:
    A m_a;
};

class PassVectorClassByPtr {
public:
    PassVectorClassByPtr(const std::vector<std::shared_ptr<A>>& v) : m_v(v) {
        for (auto v_i : v) std::cout << v_i->get() << "\n";
    }
protected:
    std::vector<std::shared_ptr<A>> m_v;
};

int main() {
    {
        auto a = A();
        auto c1 = PassSingleClassByRef(a);
    }
    {
        std::vector<std::shared_ptr<A>> v { std::make_shared<A>() };
        auto c2 = PassVectorClassByPtr(v);
    }
    return 0;
}
c++ c++14
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.