gpt4 book ai didi

c++ - cv::Point3f 赋值运算符是否执行 "deep"拷贝?

转载 作者:行者123 更新时间:2023-11-28 04:21:06 27 4
gpt4 key购买 nike

下面的类方法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) Is that correct or there is another explanation?

虽然看起来是正确的,但未必以有用的方式构建。您只需将 Point3f 视为一个值即可。当您获取值时,您获取的是值而不是对它的引用。
这让我想到了

b) Is there any other way around?

不是真的,如果你想引用一个值,你可以使用对它的引用、指向它的指针或与引用或指针具有相同语义的包装类型。

比如

cv::Point3f& f = totalPointCloud[i].getWorldPoint();
cv::Point3f* f1 = &totalPointCloud[i].getWorldPoint();
std::reference_wrapper<cv::Point3f> f2 = std::ref(totalPointCloud[i].getWorldPoint());

关于c++ - cv::Point3f 赋值运算符是否执行 "deep"拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com