c++ - Passing an object to a function, scope, and destructors -


recently i've been getting programming in c++ , have come across interesting while programming else.

in code below defined class pointer member gets deleted in class' destructor.

i have defined function takes test_object object argument calls 1 of get_val() method nothing more report value held in memory address pointer pointing to.

now when call function twice correctly prints value in held internal pointer correctly once, core dumps after second.

correct me if i'm wrong, believe reason happens because after first time function called object's destructor called because object has gone out of scope , destroyed.

the way think of preventing passing object reference. there other way prevent happening? seems bit dangerous pass object reference since object can modified in function call lead headaches later on.

i've tried making argument const, error stating ‘const test_object’ ‘this’ argument of ‘void test_object::get_val()’ discards qualifiers argument.get_val();

#include <iostream>  using namespace std;  class test_object {     private:     int *internal_pointer;     public:     test_object(int value)     {         internal_pointer = new int;         *internal_pointer = value;     }     ~test_object()      {         delete internal_pointer;         internal_pointer = null;     }     void get_val() { cout<<*internal_pointer<<endl; } };  void test_outsider(test_object argument) {     argument.get_val(); }  int main() {     test_object test = test_object(4);     test_outsider(test);     test_outsider(test);     return 0; } 

to start should read the rule of three.

as problems it's because objects copied, , since don't provide own copy-constructor pointer copied "as-is" leaving multiple copies pointing same allocated memory. when 1 of copies delete allocated memory in destructor, pointer invalidated copies.

you can solve problem implementing copy-constructor , copy-assignment operator.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -