Hi
I am trying to introduce a lazy initialisation using a shared pointer.
The function that performs the initialisation is a public member function and uses a lambda.
I am unsure if the lambda is correct though. A compile error is generated on the code (below).
A small subset of the code looks something like this:
The compile error generated is on line 40:Code:#include <iostream> #include <memory> #include <string> #include <mutex> class Member; using sharep = std::shared_ptr<Member>; class Member { private: std::string sname; int sage{0}; std::once_flag once_flag; public: Member(const std::string & name, int age) : sname{name}, sage{age} { } Member() {} Member ( const Member & ) = delete; // avoid copy ~Member() {} void init_profile(const std::string & name, const int age) { sname = name; } const std::string view_profile() const { return "Name : " + sname + ", age: " + std::to_string(sage) ; } void init(sharep & sptr, const std::string & name, const int age ) { std::call_once(once_flag, [](sharep & sptr){ if(!sptr) { sptr.reset(new Member);} } ); sptr->init_profile(name, age); } }; int main() { sharep sptr; sptr.init(sptr, "Harry Potter", 12); std::cout << "Profile : " << sptr->view_profile() << "\n"; return 0; }
Can anybody suggest where the code needs fixing?Code:error: ‘using sharep = class std::shared_ptr<Member> {aka class std::shared_ptr<Member>}’ has no member named ‘init’
Thanks




Reply With Quote
