Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c++ - Need "one" object, how to use "new"

I wrote;

Element element=new Element;

I got error;

homework.cpp: In function 'int main(int, char**)':
homework.cpp:227:29: error: conversion from 'Element*' to non-scalar type 'Element' requested

*** 1 errors, 0 warnings

I do not want a pointer or array of elements,

Altough should i write Element *element= new Element;. SOmebody to explain?

EDIT:

Element class:

class Element{
  public:
      Element():exists(false){};

      std::string name;
      std::string full_path_name;
      ElementType element_type;
      long element_size;
      bool exists;

  };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want to allocate a dynamic object, it would be

Element* element = new Element;

Because new returns a pointer to the object in the free store. You have to call delete element when you're done using the object to prevent memory leaks. If you want to avoid having to manually manage the memory, you can use std::unique_ptr:

std::unique_ptr<Element> element = new Element;

And element will call delete on the pointer automatically when it goes out of scope. However, are you sure you don't want to just create an automatic object?

Element element;

This creates the object in automatic storage and you don't have to manually deallocate it or use smart pointers, and it's a lot faster; it's the best way. (But make sure you don't do Element element(); which is the prototype for a function, not a variable declaration.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...