【发布时间】:2013-05-19 07:48:59
【问题描述】:
假设我有一个类,我打算直接公开为一个可实例化的类 给程序员:
class Base
{
public:
Base(std::string text) : m_text(std::move(text)) {}
private:
std::string m_text;
};
到目前为止一切顺利。这里不需要右值构造函数。 现在,在未来的某个时候,我决定扩展 Base:
class Derived : public Base
{
public:
Derived(const std::string &text) : Base(text) {}
};
这让我很烦恼:我不能在 Derived 中按值获取字符串,因为这就是 基地已经在做 - 我最终会得到 2 个副本和 1 个移动。此处的 const-reference 构造函数还会对右值执行不必要的复制。
问题:如何只复制+移动一次(就像 Base 中的简单构造函数一样)而不添加更多构造函数?
【问题讨论】:
-
为什么不能说
Derived(std::string x) : Base(std::move(x)) { }?还是只继承基础构造函数? -
@KerrekSB 将继承的构造函数放在一个答案中,它值得一票。
标签: c++ inheritance c++11 move move-semantics