В чем разница между вот этим: "CCow *cow = new CCow()" и этим: "CCow cow".
Cow.h
#pragma once
#include <string>
class CCow
{
public:
void ObtainCowInfo();
void DisplayCowInfo();
private:
std::string mName;
int mAge;
};
Cow.cpp
#include "Cow.h"
#include <iostream>
using namespace std;
void CCow::DisplayCowInfo()
{
cout << endl;
cout << "Cow Info" << endl;
cout << "+++++++++++++++" << endl;
cout << "Name: " << mName << endl;
cout << "Age: " << mAge << endl;
cout << "+++++++++++++++" << endl << endl;
}
void CCow::ObtainCowInfo()
{
cout << "Type Cow Information" << endl;
cout << "--------------------" << endl;
cout << "Cow's name: ";
cin >> mName;
// Inputting the cow's age, until valid input is inputted
bool exit = false;
while(!exit)
{
cout << "Cow's age: ";
cin >> mAge;
if(!mAge)
{
// We have an error
cout << "Invalid age, try again" << endl;
cin.clear();
cin.ignore();
continue;
}
exit = true;
}
cout << endl;
}
Main.cpp
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "Cow.h"
#include <vector>
using namespace std;
vector<CCow*> mCowListPointer;
vector<CCow> mCowsList;
void Test1(int loop)
{
for(int i = 0; i < loop; i++)
{
CCow *cow = new CCow();
cow->ObtainCowInfo();
mCowListPointer.push_back(cow);
}
cout << "Result:" << endl;
for(auto animal : mCowListPointer)
{
animal->DisplayCowInfo();
}
}
void Test2(int loop)
{
for(int i = 0; i < loop; i++)
{
CCow cow;
cow.ObtainCowInfo();
mCowsList.push_back(cow);
}
cout << "Result:" << endl;
for(auto animal : mCowsList)
{
animal.DisplayCowInfo();
}
}
int main()
{
int loop = 0;
cout << "Input loop number: ";
cin >> loop;
cout << endl;
Test1(loop);
cout << "####################" << endl;
Test2(loop);
return 0;
}
CCow cow;
и переносе с помощьюmCowsList.push_back(std::move(cow));
будет меньше тратить силы у системы, что выделяет память. А выделение памяти с помощьюnew CCow();
постоянно затормаживается программа, для выделения памяти у системы.