[英]How do I invoke copy constructor appropriately while using rvalue for an object?
Here I am trying to push an object into a vector using push_back function and rvalue of that object.在这里,我试图使用 push_back 函数和该对象的右值将一个对象推入一个向量中。 Look at the
addMovie()
function of the Movies
class below看下面
Movies
类的addMovie()
函数
#include "Movies.h"
void Movies::addMovie(std::string name, std::string rating, int watched)
{
movieColl.push_back(Movie{name,rating,watched}); //apparently I am having problem here
}
Rest of the required parts are here其余所需部件在这里
class Movies
{
public:
void addMovie(std::string name, std::string rating, int watched);
protected:
private:
std::vector <Movie> movieColl;
};
Movie class itself... I have just showed constructors here although I have implemented the other functions电影类本身...虽然我已经实现了其他功能,但我只是在这里展示了构造函数
class Movie
{
public:
Movie(std::string name,std::string rating, int watched = 0);
Movie(const Movie &obj);
Movie();
void getMovieDetails();
void addToWatchTime(int num = 1);
void setMovieDetails(std::string name,std::string rating, int watched = 0);
protected:
private:
std::string name;
std::string rating;
int watched;
};
Movie::Movie(std::string name,std::string rating, int watched):name{name},rating{rating},watched{watched}
{
//ctor
}
Movie::Movie(const Movie &obj):Movie(obj.name,obj.rating,obj.watched){}
Movie::Movie():Movie("None","NA",0){}
My MAIN Function我的主要功能
#include<iostream>
#include"Movies.h"
using namespace std;
int main()
{
Movies collection;
collection.addMovie("GG","PG",343);
return 0;
}
Basically there's two approach to solve this problem基本上有两种方法可以解决这个问题
Approach 1: Use default copy constructor provided by compiler.方法一:使用编译器提供的默认复制构造函数。
Approach 2: This ones a bit weird.方法2:这有点奇怪。 So instead of typing
所以而不是打字
movieColl.push_back(Movie{name,rating,watched});
I typed我打字
movieColl.push_back(Movie(name,rating,watched));
Basically I changed the curlys to normal parentheses and it worked..基本上我把卷曲改成了普通的括号,它起作用了..
使用 emplace_back 和 std::move。
movieColl.emplace_back(std::move(Movie{name,rating,watched}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.