我编写了一个简单的程序,可以在标准库容器中就地创建对象.这就是我写的:
#include <vector>
#include <iostream>
class AB
{
public:
explicit AB(int n);
AB(const AB& other) = delete;
AB(AB&& other);
AB& operator=(const AB& other) = delete;
AB& operator=(AB&& other) = default;
private:
int i;
};
AB::AB(int n): i( n )
{
std::cout << "Object created." << std::endl;
};
AB::AB(AB&& other): i( std::move(other.i) )
{
std::cout << "Object moved." << std::endl;
};
int main()
{
std::vector< AB > v;
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
};
Run Code Online (Sandbox Code Playgroud)
我用g ++(版本4.8.2)编译它.运行输出后,我得到:
Object created.
Object created.
Object moved.
Object …Run Code Online (Sandbox Code Playgroud)