如何使用智能指针来管理现有对象

huangapple go评论79阅读模式
英文:

How to use smart pointer to manage existing object

问题

假设我有一个从某个API生成的数据向量。仅用于绘图。

vector<double> LineData = generateData();

我还有一个执行绘图和管理数据的类。

class LineChart
{
public:
    LineChart(vector<double>* data) : m_data{ data } {}
    vector<double>* m_data;
    void plot();
};

LineChart lc{ &LineData };

由于这个向量仅用于绘图,我希望这个类完全拥有它。因此,我想将原始指针更改为unique_ptr。

通常,unique_ptr是从new或make_unique创建的,而不是从现有对象创建。我可以复制向量,然后将其移动到类中。

unique_ptr<vector<double>> data = make_unique<vector<double>>(LineData);

但是复制向量会导致不必要的开销,因为我已经有了数据。此外,原始向量会在堆栈上复制一次且无用。

那么,在这种情况下,有没有一些有效的方法将现有对象的所有权传递给类?最佳实践是什么?

英文:

Suppose I have a vector of data generated from some API. It's for plotting only.

vector&lt;double&gt; LineData = generateData();

I also have a class that do the plotting and manage the data

class LineChart
{
public:
    LineChart(vector* data):m_data{data}{}
    vector&lt;double&gt; *m_data;
    void plot();
};

LineChart lc {&amp;LineData}

Since the vector is only for plotting, I want the class to take the full ownership. So I want to change the raw pointer to a unique_ptr.

Normally, a unique_ptr is created from new or make_unique,instead of an existing object. I could make a copy of the vector, then move it to the class.

unique_ptr&lt;vector&gt; data = make_unique&lt;vector&gt;(LineData)

But there is unnecessary overhead to copy the vector, since I have the data already. Also, the original vector becomes duplicated on the stack and does nothing.

So in situation like this, are there some efficient ways to pass the ownership of existing object to the class? What's the best practice?

答案1

得分: 8

这里没有必要使用任何类型的指针,只需将数据移动到指定位置。不会复制向量数据。

class LineChart
{
public:
    LineChart(vector data) : m_data{std::move(data)} {}
    vector<double> m_data;
    void plot();
};

LineChart lc{std::move(LineData)};

你也可以直接初始化,而不使用LineData变量:

LineChart lc{generateData()};

这里std::move不是必要的,因为generateData函数的返回值是临时的,会自动移动。

英文:

There is no reason to use any kind of pointer here, just move the data into place. No copying of the vector happens.

class LineChart
{
public:
    LineChart(vector data):m_data{std::move(data)}{}
    vector&lt;double&gt; m_data;
    void plot();
};

LineChart lc {std::move(LineData)};

You could also initialise directly without using the LineData variable

LineChart lc {generateData()};

Here std::move is not necessary because the return value of the generateData function is a temporary and will be moved automatically.

huangapple
  • 本文由 发表于 2023年7月12日 22:59:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76671963.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定