一个移动构造函数需要一个常量或非常量右值引用? [英] Should a move constructor take a const or non-const rvalue reference?

查看:256
本文介绍了一个移动构造函数需要一个常量或非常量右值引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在几个地方,我已经看到了推荐的复制和移动构造函数的签名:

In several places I've seen the recommended signatures of copy and move constructors given as:

struct T
{
    T();
    T(const T& other);
    T(T&& other);
};

复制构造函数接受一个const引用,move构造函数接受一个非const常量引用。

Where the copy constructor takes a const reference, and the move constructor takes a non-const rvalue reference.

根据我可以看到,这阻止了我从一个函数返回const对象时利用move语义,例如:

As far as I can see though, this prevents me taking advantage of move semantics when returning const objects from a function, such as in the case below:

T generate_t()
{
    const T t;
    return t;
}

使用VC11 Beta, T 的复制构造函数被调用,而不是move构造函数。即使使用 return std :: move(t); 仍然调用复制构造函数。

Testing this with VC11 Beta, T's copy constructor is called, and not the move constructor. Even using return std::move(t); the copy constructor is still called.

这是有道理的,因为 t 是const所以不应该绑定到 T&& 。在移动构造函数签名中使用 const T&& 很好,但是有问题,因为其他是const,你不能null它的成员,如果他们需要被nulled out - 它只会工作,当所有成员是标量或移动构造函数与正确的签名。

I can see how this makes sense, since t is const so shouldn't bind to T&&. Using const T&& in the move constructor signature works fine, and makes sense, but then you have the problem that because other is const, you can't null its members out if they need to be nulled out - it'll only work when all members are scalars or have move constructors with the right signature.

看起来像是确保在一般情况下调用move构造函数的唯一方法是首先使 t 非const,但是我不喜欢这样做 - consting的事情是好的形式,我不会指望 T 的客户知道他们必须反对这种形式,以增加性能。

It looks like the only way to make sure the move constructor is called in the general case to have made t non-const in the first place, but I don't like doing that - consting things is good form and I wouldn't expect the client of T to know that they had to go against that form in order to increase performance.

所以,我想我的问题是双重的;首先,应该是一个移动构造函数采用一个常量或非常量右值引用?第二:我在这个推理线是对的吗?我应该停止返回的是const的

So, I guess my question is twofold; first, should a move constructor take a const or non-const rvalue reference? And second: am I right in this line of reasoning? That I should stop returning things that are const?

推荐答案

它应该是一个非 - code> rvalue reference。

It should be a non-const rvalue reference.

如果一个对象被放置在只读存储器中,你不能从它窃取资源,即使它的正式生命周期结束不久。在C ++中创建为 const 的对象允许存在只读存储器中(使用 const_cast 尝试更改它们的结果在未定义的行为)。

If an object is placed in read-only memory, you can't steal resources from it, even if its formal lifetime is ending shortly. Objects created as const in C++ are allowed to live in read-only memory (using const_cast to try to change them results in undefined behavior).

这篇关于一个移动构造函数需要一个常量或非常量右值引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆