在成员引用中安全存储移动的对象?

时间:2016-03-24 11:09:27

标签: c++ c++11 reference move-semantics

以下代码是否安全,或构建var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); WebResponse response = null; string pictureUrl = string.Empty; try { WebRequest request = WebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture?type=large&redirect", loginInfo.email)); response = request.GetResponse(); pictureUrl = response.ResponseUri.ToString(); } m_s可能是悬空参考?

C

2 个答案:

答案 0 :(得分:3)

不,它不安全,请考虑以下示例:

C c(std::string("42"));

你在构造函数中传递一个临时的。这样你就可以创建一个悬空引用。

答案 1 :(得分:2)

不,这不安全。成员const引用也不会延长临时的生命周期(因此也不是一个选项)。你应该做的是移动构造一个临时值,以“吸收”到你的班级:

class C {
public:
    C(string&& s) : m_s{std::move(s)} {} 
private:
    string m_s;
};