Intelligent Pointers

Asked

Viewed 169 times

6

I was studying smart pointers and based on this blog: https://murilo.wordpress.com/2008/12/15/smart-pointers-os-ponteiros-espertos-do-c/

#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;

1 answer

6


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

In fact, when you go looking for information about technology and other things on the Internet, you should look at the date. If it is very old, it has a great chance of being outdated 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 C memory management everything++.

That’s 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; 
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

This code is not necessary, the example is bad enough. It is creating a pointer to something that will actually use a pointer. string C++ is kind of already an intelligent pointer (internally). So that doesn’t make sense. It’s creating an indirect for something that’s already an indirect. This may be useful, but they are quite different from the applied.

  • then the example itself is bad yes but what I thought was to try to understand the functioning of this to do in my classes and structs in c++ not to have to keep manipulating pointer or worrying about deleting pointers I found interesting the proposal but I still have no idea of how to do as correctly as possible for future use in the classes or programs developed in the language...

  • More or less. Worry should always exist. This helps, but it is not something bulletproof. There’s a lot of things that could go wrong even with these pointers. Of course knowing how to use, analyzing whether it can not be some unwanted effect will cool, but it is far from simple as it is marketado

Browser other questions tagged

You are not signed in. Login or sign up in order to post.