-
June 27th, 2018, 10:29 AM
#1
Smart pointers
Hi,
I was told that my code will be greatly simplified if I start using smart pointers available in C++11. However, it is kind of hard for me to get the syntax.
In the old way I simply write:
Code:
std::vector<Foo *> m_myVector;
m_myVector.push_back( new Foo( <constructor_parameter_list> ) );
How it will convert using the new syntax?
Thank you.
-
June 27th, 2018, 11:29 AM
#2
Re: Smart pointers
Code:
std::vector<unique_ptr<Foo>> m_myVector;
m_myVector.push_back(make_unique<Foo>(<constructor_parameter_list>));
For a compilable example consider
Code:
using Foo = int;
std::vector<std::unique_ptr<Foo>> m_myVector;
m_myVector.push_back(make_unique<Foo>(20));
std::cout << *m_myVector.back() << std::endl;
you'll also need to include <memory>
For more info see https://en.cppreference.com/w/cpp/memory
when m_myvector goes out of scope, all the memory used by the unique_ptr's will be freed automatically.
Note that a unique_ptr can't be copied - only moved. If you need a smart pointer that can be copied use shared_ptr and make_shared().
Last edited by 2kaud; June 27th, 2018 at 11:34 AM.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
June 27th, 2018, 11:33 AM
#3
Re: Smart pointers
Originally Posted by OneEyeMan
How it will convert using the new syntax?
Something like this,
Code:
#include <memory>
//
class Foo {};
//
std::vector<std::shared_ptr<Foo>> m_myVector;
//
m_myVector.push_back(std::make_shared<Foo>(/* <constructor_parameter_list> */));
The C++ type usually referred to as "smart pointer" is called std::shared_ptr.
std::make_shared is a convenience function that's often used to create std::shared_ptr<> objects.
Last edited by wolle; June 27th, 2018 at 11:41 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|