-
February 18th, 2018, 10:36 AM
#1
[RESOLVED] boost shared_ptr (allocation question)
Sometimes I'll see a shared_ptr declared like this:-
Code:
shared_ptr<type> p;
and other times I'll see this;-
Code:
shared_ptr<type> p(new type);
AFAIK the first option allocates an object of type 'type' using new - so do the two declarations do anything different?
"A problem well stated is a problem half solved.” - Charles F. Kettering
-
February 18th, 2018, 11:09 AM
#2
Re: boost shared_ptr (allocation question)
I don't use boost so can't comment upon boost's implementation. But for c++11,
Code:
shared_ptr<type> p;
defines p using the default constructor The object p is empty (owns no pointer, use count of zero).
Code:
shared_ptr<type> p(new type);
defines p using the constructor that takes a pointer (returned by new type) whose ownership is taken over by the object and sets the use count to 1.
See http://www.cplusplus.com/reference/m...tr/shared_ptr/
PS. It looks like from the boost documentation that boost shared_ptr<> is the same.
default constructor
shared_ptr(); // never throws
shared_ptr(std::nullptr_t); // never throws
Effects: Constructs an empty shared_ptr.
Postconditions: use_count() == 0 && get() == 0.
Throws: nothing.
PPS It is more efficient to use make_shared(). See http://en.cppreference.com/w/cpp/mem...tr/make_shared
Last edited by 2kaud; February 18th, 2018 at 11:29 AM.
Reason: PS, PPS
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)
-
February 18th, 2018, 12:38 PM
#3
Re: boost shared_ptr (allocation question)
Originally Posted by 2kaud
But for c++11,
Code:
shared_ptr<type> p;
defines p using the default constructor The object p is empty (owns no pointer, use count of zero).
This particular emptiness is known as the nullptr.
Last edited by wolle; February 18th, 2018 at 12:42 PM.
-
February 18th, 2018, 02:45 PM
#4
Re: boost shared_ptr (allocation question)
Good explanations guys, thanks
"A problem well stated is a problem half solved.” - Charles F. Kettering
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
|