I never use pointer in my C++ code. Am I programming C++ wrong?

You are using “indirect reference in the general sense” in your C++ programming. There’s nothing wrong with that. It is almost as powerful as programming with pointers and reference (in the C++ language).


Although, there is one technicality pitfall in the way you use vector.

For software safety sake, I’ll describe that technical pitfall first. It’s more important to know about that pitfall, than to have your main question answered.

When objects are placed into a vector, the vector contains a copy of the object. These objects have addresses, from which you can create references (in the C++ sense). These addresses are stable until the next time you cause the vector to reallocate (growing, clearing), or causing the items to shift (e.g. delete an item in the middle). If you keep using addresses that are no longer valid (called pointer invalidation), it can trigger “undefined behavior” (UB). Once UB happens, anything can follow – the correctness of subsequent operation is no longer a guarantee.


In order to safely allow individual items in a C++ collection to be allocated (added) and deallocated (removed), these items will have to be allocated in the heap.

Here, the “heap” refers to the actual heap, i.e. the dynamic memory allocation system in C++. The dynamic memory allocation system allows individual allocations to be requested and relinquished.


Your programming style, which allows you to pre-allocate your vectors up-front, is comparable to the static memory allocation style (on a semantic level).

Static memory allocation style was the norm several decades ago, and is still mandated for certain safety critical systems, such as vehicle electronic control systems for the powerchain and fluidics parts, certain aircraft avionics systems, and weapons systems. However, it is less powerful than dynamic memory allocation style, since static memory allocation style puts a limit on what can be implemented. That said, for applications with well-defined, non-extensible scope (e.g. controlling a specific aspect of a mechanical system, and nothing else, not having to interface with anything else), it is possible to stay with static memory allocation style.


Some of the examples you mentioned are examples of “handle body idiom” (link).

In C++, a handle class allows its users to normally use C++ copy semantics to achieve something similar to C++ pointers and references.

OpenCV’s Mat class is a “handle” class. To illustrate this, consider this code snippet:

cv::Mat matOne(cv::Size(640, 480), CV_8UC3);
cv::Mat matTwo = matOne;

After these two lines of code, matTwo and matOne both reference the same object (the matrix or image). This is due to the design and the implementation detail of the cv::Mat class.

If you want to implement a class that behaves similarly, you will need to learn about C++ pointers and references, i.e. the knowledge that you’re curious about and felt like missing.


A bit on the “linguistics” of the word “semantics”.

In C++, the phrases “copy semantics” and “reference semantics” both refer to aspects of the C++ syntax and its usage. Thus, the use of the word “semantics” is a misnomer, when judged by the standard of the English language.

c – Pointer pointing to another pointer, how to use free correctly?

When I have a pointer pointing to another pointer like:

int *ponteiro1 = malloc(sizeof(int));
int *ponteiro2;

*ponteiro1 = 5;

ponteiro2 = ponteiro1;
free(ponteiro2);

And I'm using the free command (pointer2), so should I deallocate pointer1? If yes, should I do a treatment for pointer2?

C ++ ERROR – [Error] ISO C ++ prohibits comparison between pointer and integer [-fpermissive]

I'm learning C ++ and copied code over the Internet and modified it, but it has error when compiling – (Error) ISO C ++ forbidden comparison between the pointer and the integer (-fpermissive).

Coded:

include iostream

include stdio.h

set SIZE 200

name of tank (SIZE) (50);

sex of Arctic char (SIZE) (50);

int rg (SIZE) (50);

int cpf (SIZE) (50);

int tel (SIZE) (50);

age (SIZE) (50);

int op;

cancel recording ();

cancel the search ();

int main (void) {

cadastro();

pesquisa();

}

cancel registration () {

static int linha;

do{

    printf("nDigite o nome: ");

    scanf("%s", &nome(linha));

    printf("nDigite o sexo (F/M): ");

    scanf("%s", &sexo(linha));

    printf("nDigite o RG: ");

    scanf("%d", &rg(linha));

    printf("nDigite o CPF: ");

    scanf("%d", &cpf(linha));

    printf("nDigite a idade: ");

    scanf("%d", &idade(linha));

    printf("nDigite o telefone: ");

    scanf("%d", &tel(linha));

    printf("nDigite 1 para continuar ou 2 para sair: ");

    scanf("%d", &op);

    linha++;

}while(op==1);

}

cancel search () {

int cpfPesquisa;

int i;

do{

    printf("nDigite o CPF que deseja buscar: ");

    scanf("%d", &cpfPesquisa);

    for(i=0;i

sex (i), cpf (i), rg (i), age (i), tel (i));

        }

    }

printf("nDigite 1 para continuar pesquisando: ");

scanf("%d", &op);

}while(op==1);  

}

RFC: lightweight 2D C ++ array template with runtime allowances. The logic is that the multiplication is faster than the pursuit of the pointer

Any comments, criticisms or questions on this subject? I use this as the basis for some rectangular board toy programs like Conway's Life and the Snake. Usage includes setting the size of the map at runtime, so the type does not contain size information, only instances.

#include 

template
class Array2D {
   int y;
   type *data;
public:
   // We can't do a copy since we don't know
   // what size to allocate the array.
   Array2D(const Array2D&) = delete;
   Array2D& operator=(const Array2D&) = delete;

   Array2D(Array2D&& move) noexcept :
      y(std::exchange(move.y, 0)),
      data(std::exchange(move.data, nullptr)) {}

   Array2D& operator=(Array2D&& move) noexcept {
      std::swap(y, move.y);
      std::swap(data, move.data);
   }

   Array2D( int _x, int _y ) : y(_y) {
      data = new type(_x*y);
   }

   type const *operator()(int i) const {
      return data + (i * y);
   }

   type *operator()(int i) {
      return data + (i * y);
   }

   ~Array2D() {
      delete() data;
   }
};

How to call a VBscript function from a pointer obtained by Getref in a Delphi COM server application

I have a COM server application and I need to link reminders to specific events that are linked late.

My VB test script is as follows

Sub Main
  dim Frm
  Set Frm=NewForm("Form1")
  Frm.OnActivate = getRef("Frm_OnActivate")
  a= Frm.Showmodal
end Sub

sub Frm_OnActivate
  MsgBox("Activate")
end Sub

My com server has the onActivate property which is of type OleVariant.

function TALform.Get_OnActivate: OleVariant;
begin
  result:=FonActivate;
end;

procedure TALform.Set_OnActivate(Value: OleVariant);
begin
  FonActivate:=Value;
  Fform.OnActivate:=OnactivateEx
end;

My question is, after getting this value, how do I call the VBscript function from the value stored in the Olevariant (which the debugger says is of type VarDispatch)?

c – Number of cases of disease as a function of patient age (pointer variables?)

The user will give as a double entry with the first number being the number of disease cases of a specific age, I have to link "number of cases" with "age" and be able to edit this number of cases, it has the possibility of receiving more cases for an age already mentioned earlier. In addition to that, it will give the numbers X and Y, so I have to print the number of cases related to the ages between X and Y. Any clue? I know this is related to pointer variables, but I'm not sure exactly how to use it (if someone can show me sample codes with this type of variable, I'd be grateful). The language I use is C.

Fixed Unity line rendering for pointer drawing an irregular line

I think I am using the standard Oculus configuration of the SDK using OVRCameraRig. I also have a LaserPointer.

But in VR on my Rift, the line looks like this.

enter description of image here

Any idea what I'm doing wrong? Before, it was right. Now this is not the case. I don't know what I changed.

x server – Fixed misaligned mouse pointer in XMing with X2GO

Using X2Go with "multi-window" mode for better integration in the office, I cannot use the builtin vcxsrv X-Server because it hangs when opening a new one git gui or gitk the window.

On the other hand, when in use XMing (version 6.9.0.31) with options -clipboard -dpi 120 -multiwindow, programs respond to the mouse as if the pointer were about 100 pixels down from where it was displayed.

applications – KYOCERA 6910,. pointer finger

I can't get rid of the pointer finger in my note bar. Ty, Cam
and I want to know, Anderw T. "Why did you delete my question about it ¿Was it too difficult? Something maybe Meta Andrew T. Unable to resolve. Hope you answer and don't don't just kill the question ..

java – null pointer exception when trying to execute @PUT

I test the puter's put but give a null pointer exception when I try to execute @put


    @PUT
    @Path("/{idCliente}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response atualizarCliente(@PathParam("idCliente") int id, Cliente cliente) throws Exception {
        Cliente atualizarCliente = clienteDao.encontrarPorId(cliente.getIdCliente());
        System.out.println(cliente.toString());

        atualizarCliente.setIdCliente(cliente.getIdCliente());
        atualizarCliente.setNome(cliente.getNome());
        atualizarCliente.setCpf(cliente.getCpf());
        atualizarCliente.setEmail(cliente.getEmail());
        atualizarCliente.setDataDeNascimento(cliente.getDataDeNascimento());

        clienteDao.atualizar(atualizarCliente);

        return Response.ok().build();
    }
public boolean atualizar(Cliente cliente) throws Exception {
        boolean sucessoUpdate = false;

        String sql = " UPDATE CLIENTE SET NOME = ? , CPF = ? , EMAIL = ? , DATA_NASCIMENTO = ? WHERE IDCLIENTE = "
                + cliente.getIdCliente();

        Connection conexao = Banco.getConnection();
        PreparedStatement prepStmt = Banco.getPreparedStatement(conexao, sql);

        try {
            Date data = new SimpleDateFormat("yyyy-MM-dd").parse(cliente.getDataDeNascimento());

            prepStmt.setString(1, cliente.getNome());
            prepStmt.setString(2, cliente.getCpf());
            prepStmt.setString(3, cliente.getEmail());
            prepStmt.setDate(4, new java.sql.Date(data.getTime()));

            int codigoRetorno = prepStmt.executeUpdate(sql);

            if (codigoRetorno == 1) {
                sucessoUpdate = true;
            }

        } catch (SQLException e) {
            System.out.println("Erro ao atualizar Cliente. Causa: " + e.getMessage());
        } finally {
            Banco.closePreparedStatement(prepStmt);
            Banco.closeConnection(conexao);
        }

        return sucessoUpdate;
    }

    public Cliente encontrarPorId(int id) {
        Cliente cliente = new Cliente();

        Connection conn = Banco.getConnection();
        Statement stmt = Banco.getStatement(conn);
        ResultSet rs = null;

        String query = "SELECT * FROM CLIENTE WHERE IDCLIENTE = " + id;
        try {
            rs = stmt.executeQuery(query);
            if (rs.next()) {
                cliente.setIdCliente(rs.getInt(1));
                cliente.setNome(rs.getString(2));
                cliente.setCpf(rs.getString(3));
                cliente.setEmail(rs.getString(4));
                cliente.setDataDeNascimento(rs.getString(5));
            }
        } catch (SQLException e) {
            System.out.println(
                    "Erro ao executar a Query que verifica existência de Cliente por ID. Erro:" + e.getMessage());
        } finally {
            Banco.closeResultSet(rs);
            Banco.closeStatement(stmt);
            Banco.closeConnection(conn);
        }
        return cliente;
    }

and I put the url http: // localhost: 8080 / api / clients / 1 with the body in json on the factor

  {
    "IDCLIENTE": 1,
    "NOME": "Alice",
    "CPF": "11111111112",
    "EMAIL": "alice@gmail.com",
    "DATADENASCIMENTO": "1998-03-31"
    }