C++ create new pointer from existing value

  arguments, c++, pointers

How do i create a pointer from a value argument?

attempt 1

template<typename T1, typename T2>
class Both {
public:
  T1 *lx;
  T2 *rx;
  Both(T1 _lx, T2 _rx) {
    lx = new T1;
    rx = new T2;
    *lx = _lx;
    *rx = _rx;
  }
  ~Both() {
    delete lx;
    delete rx;
  }
};

class cls {
public:
  int x;
  cls(int v) : x(v) {}
};

Both<cls, cls> b(cls(1), cls(2));

This will cause an error

error: no matching constructor for initialization of ‘cls’
lx = new T1;

And I would not want to enforce all arguments for Both must have a default empty constructor.

attempt 0

Prior to this I attempted to implement Both as

Both(T1 _lx, T2 _rx) : lx(&_lx) rx(&_rx) {}

And I got a warning

warning: initializing pointer member ‘rx’ with the stack address of parameter ‘_rx’ [-Wdangling-field] Both(T1 _lx, T2 _rx) : lx(&_lx), rx(&_rx) {}

attempt 2

Both(T1 _lx, T2 _rx) {
  lx = (T1*) malloc (sizeof(T1));
  rx = (T2*) malloc (sizeof(T2));
  *lx = _lx;
  *rx = _rx;
}

gives a abort signal

FAILED: {Unknown expression after the reported line} due to a fatal error condition:
SIGABRT – Abort (abnormal termination) signal

My intended use case for Both is for the user to call delete manually after they are done

Thus to reiterate, how do I convert a non pointer value passed from an argument to a pointer?

Source: Windows Questions C++

LEAVE A COMMENT