Reputation: 331
The following class method Augmented3dPoint::getWorldPoint()
returns a reference to its member cv::Point3f world_point;
class Augmented3dPoint {
private:
cv::Point3f world_point;
public:
cv::Point3f& getWorldPoint () {
return world_point;
}
};
I am calling this in main()
through the following code (totalPointCloud is 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
What I want to do is achieve the minimum copying of variables. But, the previous code apparently does a "deep" copy...
a) Is that correct or there is another explanation?
b) I have tried the following
cv::Point3f& f = totalPointCloud[i].getWorldPoint();
f.x = 300;
f = totalPointCloud[i].getWorldPoint();
std::cout << f.x << f.y << f.z << std::endl;
which seems to directly affect class member variable world_point and avoids a "deep" copy, since its X coordinate is now 300. Is there any other way around?
Thanks a lot.
Upvotes: 0
Views: 524
Reputation: 8284
a) Is that correct or there is another explanation?
Seems correct although, not necessarily framed in a helpful way. You need to just think of a Point3f
as a value. When you get the value, you get the value not a reference to it.
Which leads me to
b) Is there any other way around?
Not really, if you want a reference to a value, you can either use a reference to it, a pointer to it or a wrapper type with the same semantics as a reference or pointer.
So things like
cv::Point3f& f = totalPointCloud[i].getWorldPoint();
cv::Point3f* f1 = &totalPointCloud[i].getWorldPoint();
std::reference_wrapper<cv::Point3f> f2 = std::ref(totalPointCloud[i].getWorldPoint());
Upvotes: 1