Lifetime of a temporary passed in operator[](const std::string& k)

D

Daniel

Is this code safe?

class A
{
public:
class Proxy
{
public:
friend class A;

operator A&()
{
return val_.get(k_);
}

operator const A&() const
{
return val_.get(k_);
}
private:
Proxy& operator = (const Proxy& other) {/* do nothing */}
Proxy(const Proxy& proxy)
: val_(proxy.val_), k_(proxy.k_)
{
}
Proxy(A& val, const std::string& k)
: val_(val), k_(k)
{
}

A& val_;
const std::string& k_;
};

A& get(const std::string& k)
{
// In real code, looks up another A instance using k
return *this;
}

const A& get(const std::string& k) const
{
// In real code, looks up another A instance using k
return *this;
}

Proxy operator[](const std::string& k)
{
return Proxy(*this,k);
}
};

A a;
A b = a["key"];

Do I have to worry about the lifetime of the temporary k_ held in Proxy?

Thanks!
Daniel
 
V

Victor Bazarov

Is this code safe?

class A
{
public:
class Proxy
{
public:
friend class A;

operator A&()
{
return val_.get(k_);
}

operator const A&() const
{
return val_.get(k_);
}
private:
Proxy& operator = (const Proxy& other) {/* do nothing */}
Proxy(const Proxy& proxy)
: val_(proxy.val_), k_(proxy.k_)
{
}
Proxy(A& val, const std::string& k)
: val_(val), k_(k)
{
}

A& val_;
const std::string& k_;
};

A& get(const std::string& k)
{
// In real code, looks up another A instance using k
return *this;
}

const A& get(const std::string& k) const
{
// In real code, looks up another A instance using k
return *this;
}

Proxy operator[](const std::string& k)
{
return Proxy(*this,k);
}
};

A a;
A b = a["key"];

Do I have to worry about the lifetime of the temporary k_ held in Proxy?

Unless somehow (and you don't show all the use of A::proxy an object A
can have) the object 'b' retains the reference to the string, there is
no need to worry. The temporary string created to be passed as the
argument to the operator[] has the lifetime until the end of the object
'b' initialization.

V
 
D

Daniel

Do I have to worry about the lifetime of the temporary k_ held in Proxy?

Unless somehow (and you don't show all the use of A::proxy an object A

can have) the object 'b' retains the reference to the string, there is

no need to worry. The temporary string created to be passed as the

argument to the operator[] has the lifetime until the end of the object

'b' initialization.
Thanks! Appreciate the response.

Best regards,
Daniel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top