Need “one” object, how to use “new”

試著忘記壹切 提交于 2019-12-13 09:21:40

问题


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;

  };

回答1:


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.)




回答2:


If your object does not need any arguments you can do

Element * element=new Element();

If your object needs arguments in the constructor they need to be passed by creation

Element * element=new Element(argument1, argument2);



回答3:


Calling:

Element * element = new Element;

Will give you a pointer to an element on the heap which you will later need to delete. You can use the members of this with element->my_member.

Caling:

Element element; will create an object on the stack which will not need to be deleted and will be invalidated when it goes out of scope. You can use the members of this with element.my_member.




回答4:


By calling new you are allocating an object in heap memory, not in stack( in case of Element element;, for example).

The correct way is to use Element *element= new Element();

This won't allocate memory for multiple objects (in that case you'd written new[])



来源:https://stackoverflow.com/questions/10564706/need-one-object-how-to-use-new

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!