मुझे रेंज-लूप का उपयोग करते समय संदर्भों को लटकाना पड़ रहा है। जाहिर हैमैं अभिव्यक्ति के लिए एक अस्थायी जीवनकाल कैसे बढ़ा सकता हूं?
Wheel()
Wheel()
Bike()
~Bike() with 0 inflated wheels.
~Wheel()
~Wheel()
Wheel::inflate()
Wheel::inflate()
कुछ बहुत गलत हो रहा है: निम्नलिखित सी ++ 14 अभिव्यक्ति (पूर्ण उदाहरण नीचे कार्यक्रम) पर विचार करें:
for(auto& wheel: Bike().wheels_reference())
wheel.inflate();
यह उत्पादन होता है। पहियों उनके जीवनकाल परे एक्सेस किया जाता है और परिणाम 0 है, नहीं की उम्मीद 2.
एक आसान ठीक main
में Bike
के लिए एक चर शुरू करने की है। हालांकि, मैं main
या Wheel
में कोड को नियंत्रित नहीं करता हूं। मैं केवल संरचना Bike
बदल सकता हूं।
क्या इस उदाहरण को ठीक करने के लिए कोई तरीका है केवल Bike
बदलकर?
एक सफल समाधान समाधान या तो संकलन समय में विफल हो जाएगा, या 2 फुलाए गए टायरों की गणना करेगा और किसी भी वस्तु को उनके जीवनकाल से परे स्पर्श नहीं करेगा।
परिशिष्ट:
#include <memory>
struct Bike
{
// Bike() { cout << " FakeBike()" << endl; }
// ~Bike() { cout << "~FakeBike()" << endl; }
struct RealBike;
struct Wrap {
std::shared_ptr<RealBike> parent;
auto begin() { return parent->wheels.begin(); }
auto end() { return parent->wheels.end(); }
};
struct RealBike {
RealBike() { cout << " Bike()" << endl; }
~RealBike() {
cout << "~Bike() with " << std::count_if(wheels.begin(), wheels.end(),
[](auto& w) { return w.inflated; }) << " inflated wheels." << endl;
}
std::array<Wheel, 2> wheels;
};
std::shared_ptr<RealBike> real = std::make_shared<RealBike>();
Wrap wheels_reference() { return Wrap{real}; }
};
क्या मुझे पसंद नहीं है कि यह लपेटकर सभी std::array<Wheel, 2>
की एपीआई की आवश्यकता है: संकलन तैयार स्रोत
#include <cstdlib>
#include <iostream>
#include <array>
#include <algorithm>
using std::cout;
using std::endl;
struct Wheel
{
Wheel() { cout << " Wheel()" << endl; }
~Wheel() { cout << "~Wheel()" << endl; }
void inflate() { inflated = true; cout << " Wheel::inflate()" << endl; }
bool inflated = false;
};
struct Bike
{
Bike() { cout << " Bike()" << endl; }
~Bike() {
cout << "~Bike() with " << std::count_if(wheels.begin(), wheels.end(),
[](auto& w) { return w.inflated; }) << " inflated wheels." << endl;
}
std::array<Wheel, 2>& wheels_reference() { return wheels; }
std::array<Wheel, 2> wheels{Wheel(), Wheel()};
};
int main()
{
for(auto& wheel: Bike().wheels_reference())
wheel.inflate();
return EXIT_SUCCESS;
}
यदि केवल 'बाइक' में, फ़ंक्शन 'संदर्भ' की तुलना में, मान द्वारा सरणी वापस करनी चाहिए, संदर्भ के अनुसार नहीं, लेकिन मुझे लगता है कि यह वही नहीं है जो आप चाहते हैं। – ForEveR
@ForEveR लेकिन 'ऑटो' 'उस से बंधे नहीं जा सका। – TartanLlama
@ForEveR: हालांकि यह उपयोग के बाद नष्ट हो जाता है, यह समाधान के लिए मेरी शर्तों को पूरा नहीं करता है। मुद्रित मान 0 होगा, न कि 2. – Remco