Question for a senior C++ developer. Dare you?



  • What must be in SR.h to achieve desired printed values?

    #include <stdio.h>
    #include "SR.h"
    
    int main()
    {
        int j = 1;
        int a[] = {2, 3};
        {
            SR x(j), y(a[0]), z(a[1]);
    
            j = a[0];
            a[0] = a[1];
            a[1] = j;
    
            printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
            //        j = 2, a = {3, 2} - we want that the printed be this
        }
        printf("j = %d, a = {%d, %d}\n", j, a[0], a[1]);
        //        j = 1, a = {2, 3} -  - we want that the printed be this
    }
    ```

  • Moderators

    @Kofr
    so you want instead of printing

    j = 2, a = {3, 2}
    j = 2, a = {3, 2}
    

    it should print

    j = 2, a = {3, 2}
    j = 1, a = {2, 3}
    

    right???

    If so you need to get around the scoping and create new "inner" variables" and create a copy of the "outer" variable values.


  • Lifetime Qt Champion

    Hi,

    To add to @raven-worx, looks like SR is just useless since it's not used anywhere.



  • @SGaist solution is made by SR.


  • Qt Champions 2016

    Here:

    template<class T>
    class SR
    {
    public:
        SR(T & v)
            : ref(v), val(v)
        {
        }
    
        ~SR()
        {
            ref = val;
        }
    
    private:
        T & ref, val;
    }
    

    But what would be the purpose of this, beside being an example of bad programming?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.