英文:
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<double> 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<double> *m_data;
void plot();
};
LineChart lc {&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<vector> data = make_unique<vector>(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<double> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论