我有课
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/