相关疑难解决方法(0)

这里不是const修饰符吗?

" Effective C++ "第3项说"尽可能使用const",它给出了一个例子:

const Rational operator*(const Rational& lhs, 
                            const Rational& rhs);
Run Code Online (Sandbox Code Playgroud)

防止客户端犯下这样的暴行:

Rational a, b, c;
...
(a * b) = c;   // invoke operator= on the result of a*b!
Run Code Online (Sandbox Code Playgroud)

但是,函数的非参考返回值是否已经是一个rvalue?那么为什么还要这么做呢?

c++ coding-style const rvalue c++11

45
推荐指数
3
解决办法
3110
查看次数

移动语义并返回const值

我有习惯(?!?!?)将所有内容作为"const"值返回.像这样...

struct s;

s const make_s();

s const &s0 = make_s();
s const s1 = make_s();
Run Code Online (Sandbox Code Playgroud)

使用移动操作和r值引用以及以下功能......

void take_s(s &&s0);
void take_s(s const &&s0);  //  Doesn't make sense
Run Code Online (Sandbox Code Playgroud)

我不能再写了......

take_s(make_s());
Run Code Online (Sandbox Code Playgroud)

我开始使用返回const值的约定的主要原因是为了防止有人编写这样的代码......

make_s().mutating_member_function();
Run Code Online (Sandbox Code Playgroud)

用例如下......

struct c_str_proxy {
    std::string m_s;

    c_str_proxy(std::string &&s) : m_s(std::move(s)) {
    }
};

c_str_proxy c_str(std::string &&s) {
    return c_str_proxy(s);
}

char const * const c_str(std::string const &s) {
    return s.c_str();
}

std::vector < std::string > const &v = make_v();
std::puts(c_str(boost::join(v, ", ")));

std::string const my_join(std::vector < std::string > …
Run Code Online (Sandbox Code Playgroud)

c++ const return-value move-semantics c++11

3
推荐指数
1
解决办法
1798
查看次数

标签 统计

c++ ×2

c++11 ×2

const ×2

coding-style ×1

move-semantics ×1

return-value ×1

rvalue ×1