Smart Pointers

6

I was studying smart pointers and based on this blog: link

#include <iostream>

template <class T>  class SmartPointer 
{
        T *ptr; public:
        SmartPointer(T *p):ptr(p) {}

        ~SmartPointer() {delete ptr;}

        T& operator*() {return *ptr;}

        T* operator->() {return ptr;} 
};


int main() 
{
  SmartPointer str(new std::string("Testando Smart Pointers"));
  std::cout << *str << " size: " << str->size() << std::endl; 
}

But when compiling the same it returns this error:

ex2.cxx: In function ‘int main()’: ex2.cxx:20:18: error: missing
template arguments before ‘str’
     SmartPointer str(new std::string("Testando Smart Pointers"));
                  ^~~ ex2.cxx:21:19: error: ‘str’ was not declared in this scope
     std::cout << *str << " size: " << str->size() << std::endl;
    
asked by anonymous 03.12.2017 / 10:44

1 answer

6

The error is in the original code itself, so you already know that the font is not good.

In fact when going to look for information about technology and other things on the internet should look at the date. If it is too old it has a great chance of being out of place if it is not a foundation.

This is a case, there teaches things that should not be done anymore. In fact there has always been controversy in that use.

To learn use sources that have been evaluated, like Wikipedia . And see the documentation of all C ++ memory management .

How it works:

#include <iostream>
#include <memory>

int main() {
    auto str = std::make_unique<std::string>("Testando Smart Pointers");
    std::cout << *str.get() << " size: " << str->size() << std::endl; 
}

See running on ideone . Also I placed GitHub for future reference .

This code is not required. The example is bad already. You are creating a pointer to something that will actually use a pointer. string of C ++ means that it is already a smart pointer (internally). So this does not make sense. You are creating an indirection for something that is already an indirection. This may even be useful, but they are very different cases from the one applied.

    
03.12.2017 / 11:57