c++ - 使具有引用成员的类可复制和可移动

标签 c++

我有课

class Route
{
    public:
    Route(std::vector<int> locationIds, const ILocationSource&);
    double getRouteLength() const;
    bool operator<(const Route&);

    private:
    std::vector<int> locationIds_;
    const ILocationSource& locationSource_;
};

getRouteLength()通过遍历 locationIds_ 计算路线长度并从 ILocationSource 获取坐标:

class ILocationSource
{
    public:
    virtual Location getLocation(size_t n) = 0;
};

struct Location
{
    double x, y, z;
}

我不想将坐标存储在 Route 中因为Location大约是 int 的 6 倍如果我在内存中有很多长路径,ID 可能很重要。

问题是 Route::locationSource_使得难以实现移动语义,因此尝试调用 std::sort()std::vector<Route> 上提示。

简单的解决方案是更改 locationSource_我猜是指向 const 的指针,但我想知道是否有人能看到更好的解决方案或模式。单例不是一个选项,因为可能有多个 ILocationService 的实现。同时。

最佳答案

你应该只使用 shared_ptr而不是引用:

std::shared_ptr<const ILocationSource> locationSource_;

它解决了您的复制/移动问题,并且您获得(共享)ILocationSource 实例的所有权,这保证了 ILocationSource 只要 Route 就有效 需要它。

除此之外,考虑通过 ref 或 const ref 传递 locationIds

关于c++ - 使具有引用成员的类可复制和可移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58777393/

相关文章:

c++ - 指针的元素保存为乱码

c++ - 我们可以在 C++ 中使用 "wrap"模板类和非模板类吗?

c++ - 当我声明vector <Point2f>函数时,opencv c++ “missing ' ;' before ' <' ”

c++ - 为什么在析构函数中抛出异常时不调用重载删除?

c++ - 从函数返回字符数组

c++ - 关于类名的arduino c++问题

c++ - 替换 VC++ 8 中的 auto_ptr

c++ - 强制 C++ 结构紧密打包

c++ - Qt:UI 与 c++ 对比 xml 对比 qml

c++ - STL vector : undefined behaviour when calling data() on a temporary?