下面的类方法Augmented3dPoint::getWorldPoint()返回对其成员cv::Point3f world_point;的引用
class Augmented3dPoint {
private:
cv::Point3f world_point;
public:
cv::Point3f& getWorldPoint () {
return world_point;
}
};我在main()中通过以下代码调用它(totalPointCloud是std::vector<Augmented3dPoint> totalPointCloud;)
cv::Point3f f;
f = totalPointCloud[i].getWorldPoint(); // <---- Probably "deep" copy applied, why?
f.x = 300; // Try to change a value to see if it is reflected on the original world_point
f = totalPointCloud[i].getWorldPoint();
std::cout << f.x << f.y << f.z << std::endl; // The change is not reflected
//and I get as the result the original world_point,
//which means f is another copy of world_point with 300 in X coordinate我想要做的是实现变量的最小复制。但是,前面的代码显然是“深”复制的..。
a)是正确的还是有另一种解释?
b) --我尝试了以下几种方法
cv::Point3f& f = totalPointCloud[i].getWorldPoint();
f.x = 300;
f = totalPointCloud[i].getWorldPoint();
std::cout << f.x << f.y << f.z << std::endl;这似乎直接影响了类成员变量world_point,并避免了“深”副本,因为它的X坐标现在是300。还有别的路吗?
非常感谢。
发布于 2019-03-31 13:46:08
( a)这是正确的,还是有另一种解释?
似乎是正确的,虽然,不一定是以一种有益的方式。您只需将Point3f看作一个值。当你得到这个值时,你得到的是值,而不是它的引用。
这让我觉得
( b)还有其他办法吗?
实际上,如果您想要引用某个值,可以使用对它的引用、指向它的指针或具有与引用或指针相同的语义的包装类型。
所以这样的事情
cv::Point3f& f = totalPointCloud[i].getWorldPoint();
cv::Point3f* f1 = &totalPointCloud[i].getWorldPoint();
std::reference_wrapper<cv::Point3f> f2 = std::ref(totalPointCloud[i].getWorldPoint());https://stackoverflow.com/questions/55441478
复制相似问题