Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::shared_ptr usage and information

I am trying to use std::shared_ptr in my code. I have seen there have been other questions on the subject, but I am still getting a compiler error. Have I got the right version of gcc and setup?

What I have done:

I have tried to compile my code with both headers separately — <memory> and <tr1/memory> but still get the errors below in both cases.

The version of gcc I am using is

gcc --version
gcc (GCC) 4.3.2

When I include <memory> header I use std::shared_ptr and with the <tr1/memory> header I use std::tr1::shared_ptr? Is this correct?

I have set up the shared_ptr as follows:

std::shared_ptr<A*> ptr_A = shared_ptr( new A() );

The error I get is as follows:

src/WH.cxx:156: error: 'shared_ptr' is not a member of 'std'
src/WH.cxx:162: error: 'shared_ptr' was not declared in this scope

when I try the <tr1/memory> header

src/WH.cxx:156: error: 'std::tr1' has not been declared
src/WH.cxx:162: error: 'shared_ptr' was not declared in this scope

Looks like I am not including something correctly. Any ideas?

I know the boost library has shared_ptr but these libraries are not an option for me at the moment.

EDIT: Just to add, my compiler options are as follows: g++ -O3 -g3 -m32 -fPIC -Wno-deprecated -pthread -m32 Am I missing anything?

P.S. Is there any useful literature on the std smart pointers?

like image 513
MWright Avatar asked Nov 17 '11 17:11

MWright


People also ask

What is the use of shared_ptr?

shared_ptr is also helpful in C++ Standard Library containers when you're using algorithms that copy elements. You can wrap elements in a shared_ptr , and then copy it into other containers with the understanding that the underlying memory is valid as long as you need it, and no longer.

What is a shared_ptr in C++?

std::shared_ptr is a smart pointer that retains shared ownership of an object through a pointer. Several shared_ptr objects may own the same object.

What does shared_ptr get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

Who owns a shared_ptr?

shared_ptr objects can only share ownership by copying their value: If two shared_ptr are constructed (or made) from the same (non-shared_ptr) pointer, they will both be owning the pointer without sharing it, causing potential access problems when one of them releases it (deleting its managed object) and leaving the ...


1 Answers

std::tr1::shared_ptr is part of the TR1 additions to the C++ STL.
With GCC, it is available either through #include <tr1/memory> (GCC 4.1) or #include <memory> (GCC 4.3)

like image 110
Alok Save Avatar answered Sep 25 '22 06:09

Alok Save