creating an object in dynamic memory

Hello, i am unfamiliar with c++ and I was wondering how you could make helper function to create an object in dynamic memmory and return its address

class_name* function_name()
e.g.
if my class name is Person and function name is createPerson
its:
Person* createPerson();

I get this is how you would declare the function, but how would you code it?
The standard library provides smart pointers which automate resource management and helper functions to create objects with dynamic storage duration (which are accessed via smart pointers.)
https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>
#include <memory>

struct person
{
    person( std::string name, int age, int phone, std::string email )
        : name(name), age(age), phone(phone), email(email) { /* ... */ }

    std::string name ;
    int age ;
    int phone ;
    std::string email ;
};

int main()
{
    // http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
    auto pp = std::make_unique<person>( "valdimir", 19, 123456, "vladimir@.mir.edu" ) ;

    std::cout << "person{ " << pp->name << ", " << pp->age << ", " << pp->phone
              << ", " << pp->email << " }\n" ;

    // the person object is automagically deleted when the smart pointer goes out of scope
}

http://coliru.stacked-crooked.com/a/804d3aeeae1343d1
so would you write it like this?

People* NewPerson = new People
JLBorges is demonstrating to you how you would accomplish this using smart pointers (smart pointers provide automatic memory management and are more preferable). If you do not want to use smart pointers then you would do it the way you mentioned. Just remember to de-allocate the used memory from the heap (or the freestore) once you're done with it.

1
2
3
4
5
6
People* newPerson = new People(); // newPerson now points to an object of type "People" on the heap.

...

delete newPerson;
newPerson = nullptr;


Registered users can post here. Sign in or register to post.