[英]C++: return a std::vector<> member, by reference, to a temporary object
我有兩個功能。
function1調用function2,該函數返回對對象的引用,然后使用該對象來調用公共函數。
function1(function2).returned_object.mymethod();
這是一種相當笨拙的做事方式,但確實可行。
現在我有一個問題,我需要先調用一個方法,然后再調用另一個方法,所以我需要一個臨時對象。
ClassName temp_obj = function1(function2);
temp_obj.method1();
temp_obj.method2();
我的問題是,如何聲明一個臨時對象,該對象將存儲通過引用返回的對象。 我猜我需要一個指針。
另一個問題是,temp_obj包含在向量中,我擔心那里的沖突和內存泄漏。 如果使用指針,那么是否還必須使用析構函數?
以下是相關代碼:
bool Machine::perform_function(std::vector<Job>& jobs) {
bool add = true;
if (can_fail) {
add = coin_toss();
}
for (int i = 0; i < my_jobs.size(); i++) {
if (add) {
find_job(my_jobs[i], jobs).toggle(name, item_name, true);
}
if (!add) {
find_job(my_jobs[i], jobs).toggle(name, item_name, false);
}
}
return add;
}
Job& Machine::find_job(std::string jobname, std::vector<Job>& jobs) {
for (int i = 0; i < jobs.size(); i++) {
if (jobs[i].is_job(jobname)) {
return jobs[i];
}
}
}
您需要一個臨時變量,但是該臨時變量可以作為引用,因此無需進行任何復制即可安全使用它。
但更好的是,您可以使用<algorithm>
函數來執行所需的操作,而無需重新發明輪子:
std::string name = ...;
auto it = std::find_if(begin(jobs), end(jobs), [&name] (const Job& job) { return job.is_job(name); });
if (it != jobs.end())
{
it->method1();
it->method2();
}
將結果存儲為參考完全可以:
ClassName & temp_obj = function1(function2);
temp_obj.method1();
temp_obj.method2();
您在這里的其他問題:
另一個問題是,temp_obj包含在向量中,我擔心那里的沖突和內存泄漏。
可以返回jobs[i]
作為參考。 向量上的operator[]
本身返回引用。 如果您不以改變參考點所指的方式來修改向量,並且不存儲對已銷毀對象的參考,則可以使用它。
當您的臨時參考超出范圍時,什么也不會發生。 這只是一個參考。
假設是function1()
返回引用(您的問題尚不清楚),只需使用引用
ClassName &temp_obj = function1(function2);
temp_obj.method1();
temp_obj.method2();
如果function1()
返回const
引用,則temp
也需要為const
。
這樣做的局限性在於,一旦創建引用,就無法重新引用(使其引用另一個對象)。 例如,
ClassName &temp_obj = function1(function2); // initialisation
temp_obj = function1(some_other_function); // reassignment
temp_obj.method1();
temp_obj.method2();
即使function1()
在第二個調用中返回了不同的引用,重分配也不會重設temp
。 相反,將對要引用的對象進行分配(假設它具有有效的分配運算符)。 如果您想要一個可以隨時間引用不同對象的變量,則需要一個指針。
ClassName *temp_obj = &function1(function2); // assumes function1() returns a reference
temp_obj = &function1(some_other_function); // reassigns the pointer
temp_obj->method1();
temp_obj->method2();
您的問題不清楚。 但是,如果您要指向函數或成員函數的指針,則此處提供有關此類變量的常見問題解答。
https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.