[英]Does cv::Point3f assignment operator do a “deep” copy?
以下类方法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。还有其他方法吗?
非常感谢。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.