相关疑难解决方法(0)

std :: move是否真的需要在构造函数的初始化列表中通过值传递的重成员?

最近我从cppreference中读到了一个例子.../vector/emplace_back:

struct President
{
    std::string name;
    std::string country;
    int year;

    President(std::string p_name, std::string p_country, int p_year)
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
    {
        std::cout << "I am being constructed.\n";
    }
Run Code Online (Sandbox Code Playgroud)

我的问题:这std::move真的需要吗?我的观点是,这p_name不是在构造函数体中使用,所以,也许,语言中有一些规则默认使用移动语义?

将std :: move初始化列表添加到每个重要成员(例如std::string,std::vector)会非常烦人.想象一下用C++ 03编写的数百个KLOC项目 - 我们是否应该添加到处std::move

这个问题:move-constructor-and-initialization-list答案说:

作为一个黄金法则,无论何时你通过右值引用来获取内容,你需要在std :: move中使用它,并且每当你通过通用引用(即用&&推导出模板化类型)时,你需要在std ::里面使用它向前

但我不确定:通过价值而不是普遍的参考?

[UPDATE]

使我的问题更清楚.构造函数参数可以被视为XValue - 我的意思是到期值?

在这个例子AFAIK我们不使用std::move:

std::string getName()
{
   std::string local = "Hello SO!";
   return local; // std::move(local) is not needed nor …
Run Code Online (Sandbox Code Playgroud)

c++ language-lawyer initialization-list move-semantics c++11

34
推荐指数
3
解决办法
7321
查看次数

正确的模板方法来包装ostream

给一个班级

class ostreamWrapper
{
    private:
        ostream * str;

    public:
        ostreamWrapper operator << (const char *);
}
Run Code Online (Sandbox Code Playgroud)

where ostream * str将指向std :: cout ostreamWrapper operator << (const char *)并将给定文本发送到包装的ostream str.

在这种情况下,我只能instance << "const char * text",没有其他可打印的数据.与直接<<使用std :: cout或std :: cerr不同.

如何实现operator方法,以便接受任何类型的数据,就像std :: cout或std :: cerr一样?

c++ ostream

2
推荐指数
1
解决办法
742
查看次数