C++ 我如何知道我';我用复制还是移动?

C++ 我如何知道我';我用复制还是移动?,c++,c++14,move-semantics,C++,C++14,Move Semantics,我对C++14标准库使用移动语义的理解正确吗?换句话说,我是否可以确信我在以下程序中使用的是移动而不是复制: #include <iostream> #include <string> #include <vector> using namespace std::string_literals; std::vector<std::string> greeting() { std::vector<std::string> vs

我对C++14标准库使用移动语义的理解正确吗?换句话说,我是否可以确信我在以下程序中使用的是移动而不是复制:

#include <iostream>
#include <string>
#include <vector>

using namespace std::string_literals;

std::vector<std::string> greeting()
{
    std::vector<std::string> vs {"hello"s, "world"s};
    return vs;
}

int main()
{
    std::vector<std::string> s = greeting();
    std::cout << s[0] << " " << s[1] << "\n" ;
}
#包括
#包括
#包括
使用名称空间std::string_文本;
std::vector问候语()
{
向量vs{“hello”s,“world”s};
回报vs;
}
int main()
{
std::vector s=greeting();

std::cout在大多数情况下,复制和移动之间没有太大的区别。只有当你拥有不想复制的东西时,它才有意思。比如一个套接字或分配给对象的内存。所以只有当东西都很昂贵时才有意思(比如当你只需要其中一个时,复制一大块内存)而且你必须考虑所有权(不要有两个指针指向同一个内存,或者一个套接字等等)

在这两个示例中,最有可能发生的是编译器将执行RVO返回值优化,从而消除复制或移动的需要。Vector定义了移动,因此编译器将尽可能使用移动语义(右值语义),您可以使用std::move强制执行它。但是您的示例中没有一个会因为它而更快

如果您感到好奇,您可以实现复制和移动,并从它们向控制台写入内容

Greeting(const Greeting& g)
{
    std::cout << "Copy";
    // Copy it
}

Greeting(Greeting&& g)
{
    std::cout << "Move";
    // Move it
}

你到底想检查哪一行?哪一行代码应该是move?@rubenvb我的意思是,当从greeting(0或greetingc())调用return语句时,程序会做什么:它是复制对象(一个可能昂贵的操作)还是移动对象(一个便宜的操作).一般来说,无论何时创建临时对象(您无权访问),都是
移动语义的最佳候选对象。
Greeting(const Greeting& g)
{
    std::cout << "Copy";
    // Copy it
}

Greeting(Greeting&& g)
{
    std::cout << "Move";
    // Move it
}
Greeting foo(){ Greeing a; return a; }
Greeting a; // Normal construction
Greeting b(a); // Copy of 'a'
Greeting c(std::move(a)); // Move, 'a' will be changed
Greeting d(foo()); // Move from rvalue which is returned from foo() unless RVO kicks in