在C++ 03中,表达式是rvalue或lvalue.
在C++ 11中,表达式可以是:
两类已成为五大类.
给出以下代码:
#include <string>
void foo()
{
std::string s(std::move(""));
}
Run Code Online (Sandbox Code Playgroud)
这与apple clang(xcode 7)编译,而不是与visual studio 2015生成以下错误:
error C2440: 'return': cannot convert from 'const char [1]' to 'const char (&&)[1]'
note: You cannot bind an lvalue to an rvalue reference
main.cpp(4): note: see reference to function template instantiation 'const char (&&std::move<const char(&)[1]>(_Ty) noexcept)[1]' being compiled
with
[
_Ty=const char (&)[1]
]
Run Code Online (Sandbox Code Playgroud)
暂时忽略移动是多余的,在这种情况下哪个标准库实现更正确?
我的感觉是该类型即""是const char[1]如此std::move应该返回std::remove_reference<const char[1]&>::type&&这将是const char[1]&&.
在我看来,这应该衰败const char*.
或者我是否误解了这些规则?
我有一个C++类,它具有以下接口:
class F {
public:
F(int n, int d);
// no other constructors/assignment constructors defined
F& operator *= (const F&);
F& operator *= (int);
int n() const;
int d() const;
};
Run Code Online (Sandbox Code Playgroud)
我有以下代码:
const F a{3, 7};
const F b{5, 10};
auto result = F{a} *= b; // How does this compile?
Run Code Online (Sandbox Code Playgroud)
在Visual Studio(VS)2013下,注释行编译时没有错误.在VS2015下,产生错误C2678:
error C2678: binary '*=': no operator found
which takes a left-hand operand of type 'const F'
(or there is no acceptable conversion)
note: could be 'F &F::operator …Run Code Online (Sandbox Code Playgroud) 这是一些示例代码:
#include <iostream>
class Foo
{
public:
explicit Foo(int x) : data(x) {};
Foo& operator++()
{
data += 1;
return *this;
}
void *get_addr()
{
return (void*)this;
}
friend Foo operator + (const Foo& lhs, const Foo& rhs);
friend std::ostream& operator << (std::ostream& os, const Foo& f);
private:
int data;
};
std::ostream& operator << (std::ostream& os, const Foo& f)
{
return (os << f.data);
}
Foo operator + (const Foo& lhs, const Foo& rhs)
{
return Foo(lhs.data + rhs.data);
} …Run Code Online (Sandbox Code Playgroud) C++标准定义了以下删除的函数;
template <class T>
void ref(const T&&) = delete;
template <class T>
void cref(const T&&) = delete;
Run Code Online (Sandbox Code Playgroud)
这是为了通过禁止函数绑定到临时值(rvalues)来帮助确保函数不被滥用.
const &&绑定到所有rvalues,特别是prvalues?const &&绑定到所有"移动的对象"(xvalues;基本上是从std::move或类似的东西返回)?我可以说它应该,但我没有任何"证据".
const &&?
注意:评论中的一些清晰度,这个问题严重影响经典的右值,prvalue值类别.
我目前正在阅读本教程/ rvalue参考的解释:
http://thbecker.net/articles/rvalue_references/section_07.html
在第二段到最后一段中,作者提到" 工厂主体中T的复制构造函数的论证是一个左值 ".他所指的代码是这样的:
template<typename T, typename Arg>
shared_ptr<T> factory(Arg const & arg)
{
return shared_ptr<T>(new T(arg));
}
Run Code Online (Sandbox Code Playgroud)
我意识到new T(arg)在堆上构造一个T对象,但是返回的值不是一个临时指针值,如果不使用它会丢失(导致内存泄漏),因此是一个rvalue?
编辑:只是为了澄清,我知道在这个例子中将没有内存泄漏.我的意思是,如果指针值没有被使用,我们将无法访问构造的T对象,因此我们会得到内存泄漏.