When the proceeds of sale of real estate of an infant, insane person or cestui que trust, under the laws now in force, are invested, or required to be invested, under the direction of a court, and such infant, insane person or cestui que trust resides out of this state, on the petition of a guardian, committee or trustee, lawfully appointed or qualified in the state or country of the domicile of such infant, insane person or cestui que trust, the court under whose directions such proceeds are so invested, or required to be invested, may, with the consent of the persons residing in this state who would be the heirs of such infant, insane person or cestui que trust, if he were dead, order such proceeds to be paid and delivered to such foreign guardian, committee or trustee, or his agent or attorney, and the same may be removed by him to the state or country in which he was appointed or qualified: Provided, That whenever, in the judgment of the court, the removal of the trust subject will defeat or conflict with the provisions of the deed, will or other instrument creating the trust, the court may refuse to grant the prayer of the petition.