Side effects when passing objects to function in C++

后端 未结 3 874
渐次进展
渐次进展 2021-01-13 05:40

I have read in C++ : The Complete Reference book the following

Even though objects are passed to functions by means of the normal call-

3条回答
  •  旧巷少年郎
    2021-01-13 06:29

    Here is an example:

    class bad_design
    {
    public:
        bad_design( std::size_t size )
          : _buffer( new char[ size ] )
        {}
    
        ~bad_design()
        {
            delete[] _buffer;
        }
    
    private:
        char* _buffer;
    };
    

    Note that the class has a constructor and a destructor to handle the _buffer resource. It would also need a proper copy-constructor and assignment operator, but is such a bad design that it wasn't added. The compiler will fill those with the default implementation, that just copies the pointer _buffer.

    When calling a function:

    void f( bad_design havoc ){ ... }
    

    the copy constructor of bad_design is invoked, which will create a new object pointing to the same buffer than the one passed as an argument. As the function returns, the local copy destructor will be invoked which will delete the resources pointed by the variable used as an argument. Note that the same thing happens when doing any copy construction:

    bad_design first( 512 );
    bad_design error( first );
    bad_design error_as_well = first;
    

提交回复
热议问题