Search Results

Search found 74 results on 3 pages for 'destructors'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Can a destructor be recursive?

    - by Cubbi
    Is this program well-defined, and if not, why exactly? #include <iostream> #include <new> struct X { int cnt; X (int i) : cnt(i) {} ~X() { std::cout << "destructor called, cnt=" << cnt << std::endl; if ( cnt-- > 0 ) this->X::~X(); // explicit recursive call to dtor } }; int main() { char* buf = new char[sizeof(X)]; X* p = new(buf) X(7); p->X::~X(); // explicit call to dtor delete[] buf; } My reasoning: although invoking a destructor twice is undefined behavior, per 12.4/14, what it says exactly is this: the behavior is undefined if the destructor is invoked for an object whose lifetime has ended Which does not seem to prohibit recursive calls. While the destructor for an object is executing, the object's lifetime has not yet ended, thus it's not UB to invoke the destructor again. On the other hand, 12.4/6 says: After executing the body [...] a destructor for class X calls the destructors for X's direct members, the destructors for X's direct base classes [...] which means that after the return from a recursive invocation of a destructor, all member and base class destructors will have been called, and calling them again when returning to the previous level of recursion would be UB. Therefore, a class with no base and only POD members can have a recursive destructor without UB. Am I right?

    Read the article

  • Getting memory section information

    - by Basilevs
    Can somebody explain me how the following code works? # if defined(__ELF__) # define __SECTION_FLAGS ", \"aw\" , @progbits" /* writable flag needed for ld ".[cd]tors" sections bug workaround) */ # elif defined(__COFF__) # define __SECTION_FLAGS ", \"dr\"" /* untested, may be writable flag needed */ # endif asm ( ".section .ctors" __SECTION_FLAGS "\n" ".globl __ctors_begin__\n" "__ctors_begin__:\n" ".previous\n" ); asm /* ld ".[cd]tors" sections bug workaround */ ( ".section .ctors0" __SECTION_FLAGS "\n" ".globl __ctors0_begin__\n" "__ctors0_begin__:\n" ".previous\n" ); Similarly we are getting __ctors_end__ , __ctors0_end__ and destructors location is also obtained this way. After some ld bug workarounds all functions pointed by pointers from __ctors_begin__ to __ctors_end__ are executed. I don't know assembler and this code is impossible for me to interpret. BTW: I know that invoking C++ contructors/destructors from C is not a task to be considered safe or easy.

    Read the article

  • Which destructor is called when in C++?

    - by BastiBechtold
    I am hunting memory leaks in a program. I narrowed it down to some destructors not being called. However, I can't figure out why: class CMain : public CList { public: CMain(); virtual ~CMain(); ... } class CList : public CProc { public: CList(); virtual ~CList(); ... } CMain gets deallocated just fine, but ~CList() is never called. All parent classes of CList have virtual destructors, too. Do you have any hints about why the destructor for CList is never called?

    Read the article

  • Implementing the ‘defer’ statement from Go in Objective-C?

    - by zoul
    Hello! Today I read about the defer statement in the Go language: A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions. I thought it would be fun to implement something like this in Objective-C. Do you have some idea how to do it? I thought about dispatch finalizers, autoreleased objects and C++ destructors. Autoreleased objects: @interface Defer : NSObject {} + (id) withCode: (dispatch_block_t) block; @end @implementation Defer - (void) dealloc { block(); [super dealloc]; } @end #define defer(__x) [Defer withCode:^{__x}] - (void) function { defer(NSLog(@"Done")); … } Autoreleased objects seem like the only solution that would last at least to the end of the function, as the other solutions would trigger when the current scope ends. On the other hand they could stay in the memory much longer, which would be asking for trouble. Dispatch finalizers were my first thought, because blocks live on the stack and therefore I could easily make something execute when the stack unrolls. But after a peek in the documentation it doesn’t look like I can attach a simple “destructor” function to a block, can I? C++ destructors are about the same thing, I would create a stack-based object with a block to be executed when the destructor runs. This would have the ugly disadvantage of turning the plain .m files into Objective-C++? I don’t really think about using this stuff in production, I’m just interested in various solutions. Can you come up with something working, without obvious disadvantages? Both scope-based and function-based solutions would be interesting.

    Read the article

  • -(void)dealloc - How ? Objective - C

    - by sagar
    Please Note that - this is not similar than this question. OK. To understand my question, First of all please see both of these destructors. - (void)dealloc { [Marketdetails release]; Marketdetails=nil; [parsedarray release]; parsedarray=nil; [Marketid release]; Marketid=nil; [marketname release]; marketname=nil; [super dealloc]; } - (void)dealloc { [super dealloc]; [Marketdetails release]; Marketdetails=nil; [parsedarray release]; parsedarray=nil; [Marketid release]; Marketid=nil; [marketname release]; marketname=nil; } See, Both destructors have different code. In First Destructor first current class objects are released & then [super dealloc] is called. In second Desctructor first [super dealloc] is called. My question is as follows. Where should we write [super dealloc] ? first or last ? or it doesn't matter ?

    Read the article

  • destructor being called by subclass

    - by zero
    I'm currently learning more about php objects and constructors/destructors, but i've noticed in my code that the parent class's destructor is being called twice, I thought it was because i was extending the first class to my second class and that the second class was calling it, but this is what the php docs say about that: Like constructors, parent destructors will not be called implicitly by the engine. In order to run a parent destructor, one would have to explicitly call parent::__destruct() in the destructor body. so if it is not being called by the subclass then is it because by extended the first class that i've made a reference to the parent class making it call itself twice or I'm I way off base here? the code: <?php class test{ public $test1 = "this is a test of a pulic property"; private $test2 = "this is a test of a private property"; protected $test3 = "this is a test of a protected property"; const hello = 900000; function __construct($h){ //echo 'this is the constructor test '.$h; } function x($x2){ echo ' this is fn x'.$x2; } function y(){ print "this is fn y"; } } $obj = new test("this is an \"arg\" sent to instance of test"); class hey extends test{ function hey(){ $this->x('<br>from the host with the most'); echo ' <br>from hey class'.$this->test3; } } $obj2 = new hey(); echo $obj2::hello; ?>

    Read the article

  • Refcounted pointers on iPhone

    - by anon
    1) Refcounted pointers need stack variables to have constructors / destructors called at predictable places. 2) Objective-C, afaik, does not support the above. 3) The cocoa libraries are bound in Objective-C, not C++. Thus, my question: is there a easy way to use the Cocoa libraries, yet still have most of my app in C++ (and thus use my refcounted pointers)? Thanks! (iPhone in the title since this is mainly targeted at the iPhone)

    Read the article

  • What features would you like to see removed from C++?

    - by Justin Ethier
    This question was inspired by what-features-would-you-like-to-see-added-to-c. anBasically, C++ is a great general-purpose language. But perhaps too general and feature-rich... multiple inheritance, operator overloading, manual memory management, templates, smart pointers, virtual destructors, legacy frameworks (think MFC), and I could just go on. Is there any one feature / aspect of C++ that you would like taken away, to make our lives easier as C++ developers? One feature per answer, please.

    Read the article

  • Python - how to check if weak reference is still available

    - by Alex
    Hi all, I am passing some weakrefs from Python into C++ class, but C++ destructors are actively trying to access the ref when the real object is already dead, obviously it crashes... Is there any Python C/API approach to find out if Python reference is still alive or any other known workaround for this ? Thanks

    Read the article

  • Features to remove from C++

    - by Justin Ethier
    This question was inspired by What features would you like to see added to C++? (also see What features do you miss in C++?). C++ is a great general-purpose language, but perhaps too general and feature-rich: multiple inheritance, operator overloading, manual memory management, templates, smart pointers, virtual destructors, legacy frameworks (think MFC), and I could go on. Is there any one feature or aspect of C++ that you would like removed to make our lives easier as C++ developers? One feature per answer, please.

    Read the article

  • Purpose of PHP constructors

    - by Bharanikumar
    Hi, I am working with classes and object class structure, but not at a complex level – just classes and functions, then, in one place, instantiation. As to __construct and __destruct, please tell me very simply: what is the purpose of constructors and destructors? I know the school level theoretical explanation, but i am expecting something like in real world, as in which situations we have to use them. Provide also an example, please. Regards

    Read the article

  • C++ and system exceptions

    - by Abyx
    Why standard C++ doesn't respect system (foreign or hardware) exceptions? E.g. when null pointer dereference occurs, stack isn't unwound, destructors aren't called, and RAII doesn't work. The common advice is "to use system API". But on certain systems, specifically Win32, this doesn't work. To enable stack unwinding for this C++ code // class Foo; // void bar(const Foo&); bar(Foo(1, 2)); one should generate something like this C code Foo tempFoo; Foo_ctor(&tempFoo); __try { bar(&tempFoo); } __finally { Foo_dtor(&tempFoo); } Foo_dtor(&tempFoo); and it's impossible to implement this as C++ library. Upd: Standard doesn't forbid handling system exceptions. But it seems that popular compilers like g++ doesn't respect system exceptions on any platforms just because standard doesn't require this. The only thing that I want - is to use RAII to make code readable and program reliable. I don't want to put hand-crafted try\finally around every call to unknown code. For example in this reusable code, AbstractA::foo is such unknown code: void func(AbstractA* a, AbstractB* b) { TempFile file; a->foo(b, file); } Maybe one will pass to func such implementation of AbstractA, which every Friday will not check if b is NULL, so access violation will happen, application will terminate and temporary file will not be deleted. How many months uses will suffer because of this issue, until either author of func or author of AbstractA will do something with it? Related: Is `catch(...) { throw; }` a bad practice?

    Read the article

  • What's the proper term for a function inverse to a constructor? Deconstructor, destructor, or something else?

    - by Petr Pudlák
    Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.) Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell): newtype Wrap = Wrap { unwrap :: Int } Here Wrap is the constructor and unwrap is what? I've seen both, for example: ... Most often, one supplies smart constructors and destructors for these to ease working with them. ... at Haskell wiki, or ... The general theme here is to fuse constructor - deconstructor pairs like ... at Haskell wikibook (here it's probably meant in a bit more general sense). The questions are: How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term? And to clarify, is this terminology applicable to other functional languages, or is it used just in the Has

    Read the article

  • Object oriented wrapper around a dll

    - by Tom Davies
    So, I'm writing a C# managed wrapper around a native dll. The dll contains several hundred functions. In most cases, the first argument to each function is an opaque handle to a type internal to the dll. So, an obvious starting point for defining some classes in the wrapper would be to define classes corresponding to each of these opaque types, with each instance holding and managing the opaque handle (passed to its constructor) Things are a little awkward when dealing with callbacks from the dll. Naturally, the callback handlers in my wrapper have to be static, but the callbacks arguments invariable contain an opaque handle. In order to get from the static callback back to an object instance, I've created a static dictionary in each class, associating handles with class instances. In the constructor of each class, an entry is put into the dictionary, and this entry is then removed in the Destructors. When I receive a callback, I can then consult the dictionary to retrieve the class instance corresponding to the opaque reference. Are there any obvious flaws to this? Something that seems to be a problem is that the existence static dictionary means that the garbage collector will not act on my class instances that are otherwise unreachable. As they are never garbage collected, they never get removed from the dictionary, so the dictionary grows. It seems I might have to manually dispose of my objects, which is something absolutely would like to avoid. Can anyone suggest a good design that allows me to avoid having to do this?

    Read the article

  • What's the proper term for a function inverse to a constructor - to unwrap a value from a data type?

    - by Petr Pudlák
    Edit: I'm rephrasing the question a bit. Apparently I caused some confusion because I didn't realize that the term destructor is used in OOP for something quite different - it's a function invoked when an object is being destroyed. In functional programming we (try to) avoid mutable state so there is no such equivalent to it. (I added the proper tag to the question.) Instead, I've seen that the record field for unwrapping a value (especially for single-valued data types such as newtypes) is sometimes called destructor or perhaps deconstructor. For example, let's have (in Haskell): newtype Wrap = Wrap { unwrap :: Int } Here Wrap is the constructor and unwrap is what? The questions are: How do we call unwrap in functional programming? Deconstructor? Destructor? Or by some other term? And to clarify, is this/other terminology applicable to other functional languages, or is it used just in the Haskell? Perhaps also, is there any terminology for this in general, in non-functional languages? I've seen both terms, for example: ... Most often, one supplies smart constructors and destructors for these to ease working with them. ... at Haskell wiki, or ... The general theme here is to fuse constructor - deconstructor pairs like ... at Haskell wikibook (here it's probably meant in a bit more general sense), or newtype DList a = DL { unDL :: [a] -> [a] } The unDL function is our deconstructor, which removes the DL constructor. ... in The Real World Haskell.

    Read the article

  • Throwing a new exception while throwing an old exception

    - by FredOverflow
    If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws another exception, the first exception is silently swallowed. This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach? Any thoughts?

    Read the article

  • Compilation error when using boost serialization library

    - by Shakir
    I have been struggling with this error for a long time. The following is my code snippet. //This is the header file template<typename TElem> class ArrayList { public: /** An accessible typedef for the elements in the array. */ typedef TElem Elem; friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & ptr_; ar & size_; ar & cap_; } Elem *ptr_; // the stored or aliased array index_t size_; // number of active objects index_t cap_; // allocated size of the array; -1 if alias }; template <typename TElem> class gps_position { public: typedef TElem Elem; friend class boost::serialization::access; template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & degrees; ar & minutes; ar & seconds; } private: Elem degrees; index_t minutes; index_t seconds; }; // This is the .cc file #include #include #include #include #include #include #include #include #include "arraylist.h" int main() { // create and open a character archive for output std::ofstream ofs("filename"); // create class instance // gps_position<int> g(35.65, 59, 24.567f); gps_position<float> g; // save data to archive { boost::archive::text_oarchive oa(ofs); // write class instance to archive //oa << g; // archive and stream closed when destructors are called } // ... some time later restore the class instance to its orginal state /* gps_position<int> newg; { // create and open an archive for input std::ifstream ifs("filename"); boost::archive::text_iarchive ia(ifs); // read class state from archive ia >> newg; // archive and stream closed when destructors are called }*/ ArrayList<float> a1; ArrayList<int> a2; a1.Init(22); a2.Init(21); // a1.Resize(30); // a1.Resize(12); // a1.Resize(22); // a2.Resize(22); a1[21] = 99.0; a1[20] = 88.0; for (index_t i = 0; i < a1.size(); i++) { a1[i] = i; a1[i]++; } std::ofstream s("test.txt"); { boost::archive::text_oarchive oa(s); oa << a1; } return 0; } The following is the compilation error i get. In file included from /usr/include/boost/serialization/split_member.hpp:23, from /usr/include/boost/serialization/nvp.hpp:33, from /usr/include/boost/serialization/serialization.hpp:17, from /usr/include/boost/archive/detail/oserializer.hpp:61, from /usr/include/boost/archive/detail/interface_oarchive.hpp:24, from /usr/include/boost/archive/detail/common_oarchive.hpp:20, from /usr/include/boost/archive/basic_text_oarchive.hpp:32, from /usr/include/boost/archive/text_oarchive.hpp:31, from demo.cc:4: /usr/include/boost/serialization/access.hpp: In static member function ‘static void boost::serialization::access::serialize(Archive&, T&, unsigned int) [with Archive = boost::archive::text_oarchive, T = float]’: /usr/include/boost/serialization/serialization.hpp:74: instantiated from ‘void boost::serialization::serialize(Archive&, T&, unsigned int) [with Archive = boost::archive::text_oarchive, T = float]’ /usr/include/boost/serialization/serialization.hpp:133: instantiated from ‘void boost::serialization::serialize_adl(Archive&, T&, unsigned int) [with Archive = boost::archive::text_oarchive, T = float]’ /usr/include/boost/archive/detail/oserializer.hpp:140: instantiated from ‘void boost::archive::detail::oserializer<Archive, T>::save_object_data(boost::archive::detail::basic_oarchive&, const void*) const [with Archive = boost::archive::text_oarchive, T = float]’ demo.cc:105: instantiated from here /usr/include/boost/serialization/access.hpp:109: error: request for member ‘serialize’ in ‘t’, which is of non-class type ‘float’ Please help me out.

    Read the article

  • Throwing an exception while handling an exception

    - by FredOverflow
    If a destructor throws in C++ during stack unwinding caused by an exception, the program terminates. (That's why destructors should never throw in C++.) If a finally block is entered in Java because of an exception in the corresponding try block and that finally block throws another exception, the first exception is silently swallowed. This question crossed my mind: Could a programming language handle multiple exceptions being thrown at the same time? Would that be useful? Have you ever missed that ability? Is there a language that already supports this? Is there any experience with such an approach? Any thoughts?

    Read the article

  • Multi-Threading - Cleanup strategy at program end

    - by weismat
    What is the best way to finish a multi-threaded application in a clean way? I am starting several socket connections from the main thread in seperate sockets and wait until the end of my business day in the main thread and use currently System.Environment.Exit(0) to terminate it. This leads to an unhandled execption in one of the childs. Should I stop the threads from the list? I have been reluctant to implement any real stopping in the childs yet, thus I am wondering about the best practice. The sockets are all wrapped nicely with proper destructors for logging out and closing, but it still leads to errors.

    Read the article

  • Pure virtual destructor in interface

    - by ALOR
    Hello all. Here is my problem. I'm making C++ dll, which extensively relies on instance object exports. So i return my actual instances as a pointers to interface through some exported factory method. Interfaces i use are purely virtual, to avoid linking problame. So i need a pure virtual destructor too, and i implemented one (with empty body, as i googled it). All compiles perfectly well, except... I can't see, if the actual destructors are called or not - because when i added some std::cout << "hello destructor"; i never get to see it. I have some explicit "delete obj", that's not the problem. Am i missing something? Is there another way to delete my object through interface?

    Read the article

  • Does C++ require a destructor call for each placement new?

    - by Josh Haberman
    I understand that placement new calls are usually matched with explicit calls to the destructor. My question is: if I have no need for a destructor (no code to put there, and no member variables that have destructors) can I safely skip the explicit destructor call? Here is my use case: I want to write C++ bindings for a C API. In the C API many objects are accessible only by pointer. Instead of creating a wrapper object that contains a single pointer (which is wasteful and semantically confusing). I want to use placement new to construct an object at the address of the C object. The C++ object will do nothing in its constructor or destructor, and its methods will do nothing but delegate to the C methods. The C++ object will contain no virtual methods. I have two parts to this question. Is there any reason why this idea will not work in practice on any production compiler? Does this technically violate the C++ language spec?

    Read the article

  • C++ Memory allocation question involving vectors

    - by TheFuzz
    vector< int > vect; int *int_ptr = new int(10); vect.push_back( *int_ptr ); I under stand that every "new" needs to be followed by a "delete" at some point but does the clear() method clean this memory? What about this method of doing the same thing: vector< int > vect; int int_var = 10; vect.push_back( int_var ); From what I understand, clear() calls the variables destructors, but both vect.push_back() methods in this example push an object on the vector, not a pointer. so does the first example using an int pointer need something other than clear() to clean up memory?

    Read the article

  • Custom deleters for std::shared_ptrs

    - by Kristian D'Amato
    Is it possible to use a custom deleter after creating a std::shared_ptr without using new? My problem is that object creation is handled by a factory class and its constructors & destructors are protected, which gives a compile error, and I don't want to use new because of its drawbacks. To elaborate: I prefer to create shared pointers like this, which doesn't let you set a custom deleter (I think): auto sp1 = make_shared<Song>(L"The Beatles", L"Im Happy Just to Dance With You"); Or I can create them like this, which does let met set a deleter through an argument: auto sp2(new Song, MyDeleterFunc); But the second one uses new, which AFAIK isn't as efficient as the top sort of allocation. Maybe this is clearer: is it possible to get the benefits of make_shared<> as well as a custom deleter? Would that mean having to write an allocator?

    Read the article

< Previous Page | 1 2 3  | Next Page >