Home > Blockchain >  std::remove_reference clarification with code snippet
std::remove_reference clarification with code snippet

Time:12-09

I am trying to understand how to use the std::remove_reference functionality in type_traits. This is the piece of code that I made

template <class T>
class example {
public:
    T some_int;
    example(T inty) : some_int(inty){std::cout << "constructor called!" << "\n";}
    ~example(){std::cout << "destructor called!" << "\n";}
};

template <class T>
// return a value, hence return a copy of the object
auto function(T ptr_object) -> typename std::remove_reference<decltype(*ptr_object)>::type{
    ptr_object -> some_int = 69;
    return *ptr_object;
}

int main(){
    example<int> classy(20);
    example<int> *ptr = &classy;
    auto hello = function<decltype(ptr)>(ptr);
    std::cout << hello.some_int << std::endl;
}

so this code compiles successfully however this is the output

constructor called!
69
destructor called!
destructor called!

My aim is to return a copy of the object (and not a reference) therefore in my calculations, once i call the return in the function it should call also the constructor of the object, but this does not happen. Plus it calls the destructor 2 times. Can someone help me understand what I am getting wrong?

CodePudding user response:

When you return a copy of the object, that creates a new object, which is what you want.
So one destructor is the for the copy, and one is for the original.
In other words your code works, but you can't see the copy constructor, add the line

    example(const example& cp) : some_int(cp.some_int){std::cout << "copy constructor called!" << "\n";}

And the output is

constructor called!
copy constructor called!
69
destructor called!
destructor called!

By the way, your code looks a little clunky, but maybe that's the point? The alternative would be ...

template <class T>
T function(T* ptr_object) {
    ptr_object -> some_int = 69;
    return *ptr_object;
}

Which is more concise

EDIT: I just noticed that @Jarod42 beat me to it (again)

  •  Tags:  
  • c
  • Related