开发者

Scopeguard and parameters by reference

In this article in the Supporting Parameters by Reference section, they point out the probl开发者_运维技巧em with and provide the solution to references. My question is: why don't they just declare the parameters as references in the first place? I.e., instead of:

const Parm parm_;

do:

Parm &parm_;


It would have to be

const Param &param_;

to allow for the general case and then you would run into the same problem with trying to decrement, or in some other way modify, the parameter. The other option would be to create a lot more classes to handle const and non-const versions.

Using a reference would prevent using the result of an expression as param since the temporary reference created as the function parameter would go out of scope immediately.

Though he could remove all the const's and let it be part of the type and not allow expressions, I think there is still great value in requiring ByRef to aid in clarity.


There is one issue: in C++ temporaries cannot be bound to references, but only to const references.

Therefore, the following cannot be written:

int foo();

int& i = foo();

Unless you use Visual C++ which allows it as an extension to the language.

Also, if I used a function which returns a const reference, then it would not work either.

There is no simple solution here :)

At least not until C++0x lambdas are brought into the picture.


Because the problem with references was only a one example of how scopeguard could be used. But it should work (and work correctly) in all other cases. So having this clean up function:

void my_exit(const std::string & msg)
{
    std::cout << "my_exit: " << msg << std::endl;
}

This should work (passing temporary object):

void test()
{
    std::string msg("test_1 Hello World");
    ON_BLOCK_EXIT(&my_exit, msg.substr(0, 6));
}

This should work (passing a reference to an object that will be destroyed before the scopeguard is called):

void test()
{
    std::map<int, std::string> m;
    m[42] = "test_2";
    ON_BLOCK_EXIT(my_exit, m[42]);

    m.clear();
}

And this should work (passing a const reference):

void test(const std::string & msg)
{
    ON_BLOCK_EXIT(&my_exit, msg);
}

If the parm was const or non-const reference then those examples would either not compile or crashed when run.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜